Compare commits
16
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
08aad38986 | ||
|
|
e132c43556 | ||
|
|
e6909ae6b2 | ||
|
|
4dc7fa8f39 | ||
|
|
77dd7dbb91 | ||
|
|
86401148f7 | ||
|
|
bce8450e07 | ||
|
|
aed11f1196 | ||
|
|
97404944f5 | ||
|
|
3619aee188 | ||
|
|
f1e326ad4a | ||
|
|
a62ca4222e | ||
|
|
45858eebc4 | ||
|
|
32aad09a9a | ||
|
|
f40207480f | ||
|
|
6416ffafa2 |
@@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
+17
-35
@@ -4,9 +4,7 @@ from torch.nn.functional import group_norm
|
||||
from einops import rearrange
|
||||
|
||||
import comfy.ldm.modules.diffusionmodules.openaimodel as openaimodel
|
||||
import comfy.model_management as model_management
|
||||
from comfy.model_base import BaseModel
|
||||
from comfy.ldm.modules.attention import SpatialTransformer
|
||||
from comfy.model_base import BaseModel, model_sampling
|
||||
from nodes import KSampler
|
||||
|
||||
from .logger import logger
|
||||
@@ -18,19 +16,19 @@ from .sliding_context_sampling import SlidingContext, inject_sampling_function,
|
||||
SLIDING_CONTEXT_LENGTH = 16
|
||||
|
||||
|
||||
def forward_timestep_embed(ts, x, emb, context=None, transformer_options={}, output_shape=None):
|
||||
class ModelSamplingConfig:
|
||||
def __init__(self, beta_schedule: str):
|
||||
self.sampling_settings = {}
|
||||
self.sampling_settings["beta_schedule"] = beta_schedule
|
||||
|
||||
|
||||
def forward_timestep_embed(ts, x, emb, context=None, *args, **kwargs):
|
||||
for layer in ts:
|
||||
if isinstance(layer, openaimodel.TimestepBlock):
|
||||
x = layer(x, emb)
|
||||
elif isinstance(layer, VanillaTemporalModule):
|
||||
if isinstance(layer, VanillaTemporalModule):
|
||||
x = layer(x, context)
|
||||
elif isinstance(layer, SpatialTransformer):
|
||||
x = layer(x, context, transformer_options)
|
||||
transformer_options["current_index"] += 1
|
||||
elif isinstance(layer, openaimodel.Upsample):
|
||||
x = layer(x, output_shape=output_shape)
|
||||
else:
|
||||
x = layer(x)
|
||||
x = orig_forward_timestep_embed([layer], x, emb, context, *args, **kwargs)
|
||||
|
||||
return x
|
||||
|
||||
|
||||
@@ -49,7 +47,6 @@ def groupnorm_mm_factory(video_length: int):
|
||||
|
||||
|
||||
orig_forward_timestep_embed = openaimodel.forward_timestep_embed
|
||||
orig_maximum_batch_area = model_management.maximum_batch_area
|
||||
orig_groupnorm_forward = torch.nn.GroupNorm.forward
|
||||
|
||||
|
||||
@@ -181,32 +178,17 @@ class AnimateDiffSampler(KSampler):
|
||||
|
||||
def __init__(self) -> None:
|
||||
super().__init__()
|
||||
self.prev_beta = None
|
||||
self.prev_linear_start = None
|
||||
self.prev_linear_end = None
|
||||
self.model_sampling = None
|
||||
|
||||
def override_beta_schedule(self, model: BaseModel):
|
||||
self.prev_beta = model.get_buffer("betas").cpu().clone().detach()
|
||||
self.prev_linear_start = model.linear_start
|
||||
self.prev_linear_end = model.linear_end
|
||||
model.register_schedule(
|
||||
given_betas=None,
|
||||
beta_schedule="sqrt_linear",
|
||||
timesteps=1000,
|
||||
linear_start=0.00085,
|
||||
linear_end=0.012,
|
||||
cosine_s=8e-3,
|
||||
self.model_sampling = model.model_sampling
|
||||
model.model_sampling = model_sampling(
|
||||
ModelSamplingConfig(beta_schedule="sqrt_linear"), model_type=model.model_type
|
||||
)
|
||||
|
||||
def restore_beta_schedule(self, model: BaseModel):
|
||||
model.register_schedule(
|
||||
given_betas=self.prev_beta,
|
||||
linear_start=self.prev_linear_start,
|
||||
linear_end=self.prev_linear_end,
|
||||
)
|
||||
self.prev_beta = None
|
||||
self.prev_linear_start = None
|
||||
self.prev_linear_end = None
|
||||
model.model_sampling = self.model_sampling
|
||||
self.model_sampling = None
|
||||
|
||||
def inject_motion_module(self, model, motion_module: MotionWrapper, inject_method: str, frame_number: int):
|
||||
model = model.clone()
|
||||
|
||||
@@ -77,7 +77,7 @@ def __sliding_sample_factory(ctx: SlidingContext):
|
||||
|
||||
return orig_comfy_sample(model, *args, **kwargs, callback=callback)
|
||||
|
||||
def sampling_function(model_function, x, timestep, uncond, cond, cond_scale, model_options={}, seed=None):
|
||||
def sampling_function(model, x, timestep, uncond, cond, cond_scale, model_options={}, seed=None):
|
||||
def get_area_and_mult(conds, x_in, timestep_in):
|
||||
area = (x_in.shape[2], x_in.shape[3], 0, 0)
|
||||
strength = 1.0
|
||||
@@ -200,12 +200,12 @@ def __sliding_sample_factory(ctx: SlidingContext):
|
||||
|
||||
return out
|
||||
|
||||
def calc_cond_uncond_batch(model_function, cond, uncond, x_in, timestep, max_total_area, model_options):
|
||||
def calc_cond_uncond_batch(model, cond, uncond, x_in, timestep, model_options):
|
||||
out_cond = torch.zeros_like(x_in)
|
||||
out_count = torch.ones_like(x_in) / 100000.0
|
||||
out_count = torch.ones_like(x_in) * 1e-37
|
||||
|
||||
out_uncond = torch.zeros_like(x_in)
|
||||
out_uncond_count = torch.ones_like(x_in) / 100000.0
|
||||
out_uncond_count = torch.ones_like(x_in) * 1e-37
|
||||
|
||||
COND = 0
|
||||
UNCOND = 1
|
||||
@@ -236,9 +236,11 @@ def __sliding_sample_factory(ctx: SlidingContext):
|
||||
to_batch_temp.reverse()
|
||||
to_batch = to_batch_temp[:1]
|
||||
|
||||
free_memory = model_management.get_free_memory(x_in.device)
|
||||
for i in range(1, len(to_batch_temp) + 1):
|
||||
batch_amount = to_batch_temp[: len(to_batch_temp) // i]
|
||||
if len(batch_amount) * first_shape[0] * first_shape[2] * first_shape[3] < max_total_area:
|
||||
input_shape = [len(batch_amount) * first_shape[0]] + list(first_shape)[1:]
|
||||
if model.memory_required(input_shape) < free_memory:
|
||||
to_batch = batch_amount
|
||||
break
|
||||
|
||||
@@ -288,11 +290,11 @@ def __sliding_sample_factory(ctx: SlidingContext):
|
||||
|
||||
if "model_function_wrapper" in model_options:
|
||||
output = model_options["model_function_wrapper"](
|
||||
model_function,
|
||||
model.apply_model,
|
||||
{"input": input_x, "timestep": timestep_, "c": c, "cond_or_uncond": cond_or_uncond},
|
||||
).chunk(batch_chunks)
|
||||
else:
|
||||
output = model_function(input_x, timestep_, **c).chunk(batch_chunks)
|
||||
output = model.apply_model(input_x, timestep_, **c).chunk(batch_chunks)
|
||||
del input_x
|
||||
|
||||
for o in range(batch_chunks):
|
||||
@@ -316,14 +318,11 @@ def __sliding_sample_factory(ctx: SlidingContext):
|
||||
del out_count
|
||||
out_uncond /= out_uncond_count
|
||||
del out_uncond_count
|
||||
|
||||
return out_cond, out_uncond
|
||||
|
||||
# sliding_calc_cond_uncond_batch inspired by ashen's initial hack for 16-frame sliding context:
|
||||
# https://github.com/comfyanonymous/ComfyUI/compare/master...ashen-sensored:ComfyUI:master
|
||||
def sliding_calc_cond_uncond_batch(
|
||||
model_function, cond, uncond, x_in, timestep, max_total_area, model_options
|
||||
):
|
||||
def sliding_calc_cond_uncond_batch(model, cond, uncond, x_in, timestep, model_options):
|
||||
# figure out how input is split
|
||||
axes_factor = x.size(0) // ctx.video_length
|
||||
|
||||
@@ -386,12 +385,11 @@ def __sliding_sample_factory(ctx: SlidingContext):
|
||||
sub_uncond = get_resized_cond(uncond, full_idxs) if uncond is not None else None
|
||||
|
||||
sub_cond_out, sub_uncond_out = calc_cond_uncond_batch(
|
||||
model_function,
|
||||
model,
|
||||
sub_cond,
|
||||
sub_uncond,
|
||||
sub_x,
|
||||
sub_timestep,
|
||||
max_total_area,
|
||||
model_options,
|
||||
)
|
||||
|
||||
@@ -404,17 +402,21 @@ def __sliding_sample_factory(ctx: SlidingContext):
|
||||
uncond_final /= out_count_final
|
||||
return cond_final, uncond_final
|
||||
|
||||
max_total_area = model_management.maximum_batch_area()
|
||||
if math.isclose(cond_scale, 1.0):
|
||||
uncond = None
|
||||
|
||||
cond, uncond = sliding_calc_cond_uncond_batch(
|
||||
model_function, cond, uncond, x, timestep, max_total_area, model_options
|
||||
)
|
||||
cond, uncond = sliding_calc_cond_uncond_batch(model, cond, uncond, x, timestep, model_options)
|
||||
|
||||
if "sampler_cfg_function" in model_options:
|
||||
args = {"cond": cond, "uncond": uncond, "cond_scale": cond_scale, "timestep": timestep}
|
||||
return model_options["sampler_cfg_function"](args)
|
||||
args = {
|
||||
"cond": x - cond,
|
||||
"uncond": x - uncond,
|
||||
"cond_scale": cond_scale,
|
||||
"timestep": timestep,
|
||||
"input": x,
|
||||
"sigma": timestep,
|
||||
}
|
||||
return x - model_options["sampler_cfg_function"](args)
|
||||
else:
|
||||
return uncond + (cond - uncond) * cond_scale
|
||||
|
||||
|
||||
@@ -142,14 +142,12 @@ def uniform_constant(
|
||||
# yield if not skipped
|
||||
yield to_yield
|
||||
|
||||
|
||||
def get_context_scheduler(name: str) -> Callable:
|
||||
match name:
|
||||
case ContextSchedules.UNIFORM:
|
||||
return uniform
|
||||
case ContextSchedules.UNIFORM_CONSTANT:
|
||||
return uniform_constant
|
||||
case ContextSchedules.UNIFORM_V2:
|
||||
return uniform_v2
|
||||
case _:
|
||||
raise ValueError(f"Unknown context_overlap policy {name}")
|
||||
if name == ContextSchedules.UNIFORM:
|
||||
return uniform
|
||||
elif name == ContextSchedules.UNIFORM_CONSTANT:
|
||||
return uniform_constant
|
||||
elif name == ContextSchedules.UNIFORM_V2:
|
||||
return uniform_v2
|
||||
else:
|
||||
raise ValueError(f"Unknown context_overlap policy {name}")
|
||||
+236
-153
@@ -1,162 +1,245 @@
|
||||
import { app } from "../../../scripts/app.js";
|
||||
import { app, ANIM_PREVIEW_WIDGET } from '../../../scripts/app.js';
|
||||
import { api } from "../../../scripts/api.js";
|
||||
import { $el } from '../../../scripts/ui.js';
|
||||
import { createImageHost } from "../../../scripts/ui/imagePreview.js"
|
||||
|
||||
function offsetDOMWidget(widget, ctx, node, widgetWidth, widgetY, height) {
|
||||
const margin = 10;
|
||||
const elRect = ctx.canvas.getBoundingClientRect();
|
||||
const transform = new DOMMatrix()
|
||||
.scaleSelf(
|
||||
elRect.width / ctx.canvas.width,
|
||||
elRect.height / ctx.canvas.height
|
||||
)
|
||||
.multiplySelf(ctx.getTransform())
|
||||
.translateSelf(0, widgetY + margin);
|
||||
const URL_REGEX = /^(https?:\/\/|\/view\?|data:image\/)/;
|
||||
|
||||
const scale = new DOMMatrix().scaleSelf(transform.a, transform.d);
|
||||
Object.assign(widget.inputEl.style, {
|
||||
transformOrigin: "0 0",
|
||||
transform: scale,
|
||||
left: `${transform.e}px`,
|
||||
top: `${transform.d + transform.f}px`,
|
||||
width: `${widgetWidth}px`,
|
||||
height: `${(height || widget.parent?.inputHeight || 32) - margin}px`,
|
||||
position: "absolute",
|
||||
background: !node.color ? "" : node.color,
|
||||
color: !node.color ? "" : "white",
|
||||
zIndex: 5, //app.graph._nodes.indexOf(node),
|
||||
const style = `
|
||||
.comfy-img-preview video {
|
||||
object-fit: contain;
|
||||
width: var(--comfy-img-preview-width);
|
||||
height: var(--comfy-img-preview-height);
|
||||
}
|
||||
`;
|
||||
|
||||
export function chainCallback(object, property, callback) {
|
||||
if (object == undefined) {
|
||||
//This should not happen.
|
||||
console.error("Tried to add callback to non-existant object");
|
||||
return;
|
||||
}
|
||||
if (property in object) {
|
||||
const callback_orig = object[property];
|
||||
object[property] = function () {
|
||||
const r = callback_orig.apply(this, arguments);
|
||||
callback.apply(this, arguments);
|
||||
return r;
|
||||
};
|
||||
} else {
|
||||
object[property] = callback;
|
||||
}
|
||||
};
|
||||
|
||||
export function formatUploadedUrl(params) {
|
||||
if (params.url) {
|
||||
return params.url;
|
||||
}
|
||||
|
||||
params = { ...params };
|
||||
|
||||
if (!params.filename && params.name) {
|
||||
params.filename = params.name;
|
||||
delete params.name;
|
||||
}
|
||||
|
||||
return api.apiURL("/view?" + new URLSearchParams(params));
|
||||
};
|
||||
|
||||
export function addVideoPreview(nodeType, options = {}) {
|
||||
const createVideoNode = (url) => {
|
||||
return new Promise((cb) => {
|
||||
const videoEl = document.createElement('video');
|
||||
Object.defineProperty(videoEl, 'naturalWidth', {
|
||||
get: () => {
|
||||
return videoEl.videoWidth;
|
||||
},
|
||||
});
|
||||
Object.defineProperty(videoEl, 'naturalHeight', {
|
||||
get: () => {
|
||||
return videoEl.videoHeight;
|
||||
},
|
||||
});
|
||||
videoEl.addEventListener('loadedmetadata', () => {
|
||||
videoEl.controls = false;
|
||||
videoEl.loop = true;
|
||||
videoEl.muted = true;
|
||||
cb(videoEl);
|
||||
});
|
||||
videoEl.addEventListener('error', () => {
|
||||
cb();
|
||||
});
|
||||
videoEl.src = url;
|
||||
});
|
||||
};
|
||||
|
||||
const createImageNode = (url) => {
|
||||
return new Promise((cb) => {
|
||||
const imgEl = document.createElement('img');
|
||||
imgEl.onload = () => {
|
||||
cb(imgEl);
|
||||
};
|
||||
imgEl.addEventListener('error', () => {
|
||||
cb();
|
||||
});
|
||||
imgEl.src = url;
|
||||
});
|
||||
};
|
||||
|
||||
nodeType.prototype.onDrawBackground = function (ctx) {
|
||||
if (this.flags.collapsed) return;
|
||||
|
||||
let imageURLs = (this.images ?? []).map((i) =>
|
||||
typeof i === 'string' ? i : formatUploadedUrl(i),
|
||||
);
|
||||
let imagesChanged = false;
|
||||
|
||||
if (JSON.stringify(this.displayingImages) !== JSON.stringify(imageURLs)) {
|
||||
this.displayingImages = imageURLs;
|
||||
imagesChanged = true;
|
||||
}
|
||||
|
||||
if (!imagesChanged) return;
|
||||
if (!imageURLs.length) {
|
||||
this.imgs = null;
|
||||
this.animatedImages = false;
|
||||
return;
|
||||
}
|
||||
|
||||
const promises = imageURLs.map((url) => {
|
||||
if (url.startsWith('/view')) {
|
||||
url = window.location.origin + url;
|
||||
}
|
||||
|
||||
const u = new URL(url);
|
||||
const filename =
|
||||
u.searchParams.get('filename') || u.searchParams.get('name') || u.pathname.split('/').pop();
|
||||
const ext = filename.split('.').pop();
|
||||
const format = ['gif', 'webp', 'avif'].includes(ext) ? 'image' : 'video';
|
||||
if (format === 'video') {
|
||||
return createVideoNode(url);
|
||||
} else {
|
||||
return createImageNode(url);
|
||||
}
|
||||
});
|
||||
|
||||
Promise.all(promises)
|
||||
.then((imgs) => {
|
||||
this.imgs = imgs.filter(Boolean);
|
||||
})
|
||||
.then(() => {
|
||||
if (!this.imgs.length) return;
|
||||
|
||||
this.animatedImages = true;
|
||||
const widgetIdx = this.widgets?.findIndex((w) => w.name === ANIM_PREVIEW_WIDGET);
|
||||
|
||||
// Instead of using the canvas we'll use a IMG
|
||||
if (widgetIdx > -1) {
|
||||
// Replace content
|
||||
const widget = this.widgets[widgetIdx];
|
||||
widget.options.host.updateImages(this.imgs);
|
||||
} else {
|
||||
const host = createImageHost(this);
|
||||
this.setSizeForImage(true);
|
||||
const widget = this.addDOMWidget(ANIM_PREVIEW_WIDGET, 'img', host.el, {
|
||||
host,
|
||||
getHeight: host.getHeight,
|
||||
onDraw: host.onDraw,
|
||||
hideOnZoom: false,
|
||||
});
|
||||
widget.serializeValue = () => ({
|
||||
height: host.el.clientHeight,
|
||||
});
|
||||
// widget.computeSize = (w) => ([w, 220]);
|
||||
|
||||
widget.options.host.updateImages(this.imgs);
|
||||
}
|
||||
|
||||
this.imgs.forEach((img) => {
|
||||
if (img instanceof HTMLVideoElement) {
|
||||
img.muted = true;
|
||||
img.autoplay = true;
|
||||
img.play();
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
const { textWidget, comboWidget } = options;
|
||||
|
||||
if (textWidget) {
|
||||
chainCallback(nodeType.prototype, 'onNodeCreated', function () {
|
||||
const pathWidget = this.widgets.find((w) => w.name === textWidget);
|
||||
pathWidget._value = pathWidget.value;
|
||||
Object.defineProperty(pathWidget, 'value', {
|
||||
set: (value) => {
|
||||
pathWidget._value = value;
|
||||
pathWidget.inputEl.value = value;
|
||||
this.images = (value ?? '').split('\n').filter((url) => URL_REGEX.test(url));
|
||||
},
|
||||
get: () => {
|
||||
return pathWidget._value;
|
||||
},
|
||||
});
|
||||
pathWidget.inputEl.addEventListener('change', (e) => {
|
||||
const value = e.target.value;
|
||||
pathWidget._value = value;
|
||||
this.images = (value ?? '').split('\n').filter((url) => URL_REGEX.test(url));
|
||||
});
|
||||
|
||||
// Set value to ensure preview displays on initial add.
|
||||
pathWidget.value = pathWidget._value;
|
||||
});
|
||||
}
|
||||
|
||||
if (comboWidget) {
|
||||
chainCallback(nodeType.prototype, 'onNodeCreated', function () {
|
||||
const pathWidget = this.widgets.find((w) => w.name === comboWidget);
|
||||
pathWidget._value = pathWidget.value;
|
||||
Object.defineProperty(pathWidget, 'value', {
|
||||
set: (value) => {
|
||||
pathWidget._value = value;
|
||||
if (!value) {
|
||||
return this.images = []
|
||||
}
|
||||
|
||||
const parts = value.split("/")
|
||||
const filename = parts.pop()
|
||||
const subfolder = parts.join("/")
|
||||
const extension = filename.split(".").pop();
|
||||
const format = (["gif", "webp", "avif"].includes(extension)) ? 'image' : 'video'
|
||||
this.images = [formatUploadedUrl({ filename, subfolder, type: "input", format: format })]
|
||||
},
|
||||
get: () => {
|
||||
return pathWidget._value;
|
||||
},
|
||||
});
|
||||
|
||||
// Set value to ensure preview displays on initial add.
|
||||
pathWidget.value = pathWidget._value;
|
||||
});
|
||||
}
|
||||
|
||||
chainCallback(nodeType.prototype, "onExecuted", function (message) {
|
||||
if (message?.videos) {
|
||||
this.images = message?.videos.map(formatUploadedUrl);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export const hasWidgets = (node) => {
|
||||
if (!node.widgets || !node.widgets?.[Symbol.iterator]) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
export const cleanupNode = (node) => {
|
||||
if (!hasWidgets(node)) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const w of node.widgets) {
|
||||
if (w.canvas) {
|
||||
w.canvas.remove();
|
||||
}
|
||||
if (w.inputEl) {
|
||||
w.inputEl.remove();
|
||||
}
|
||||
// calls the widget remove callback
|
||||
w.onRemoved?.();
|
||||
}
|
||||
};
|
||||
|
||||
export const CreatePreviewElement = (name, val, format, callback) => {
|
||||
const [type] = format.split("/");
|
||||
|
||||
const w = {
|
||||
name,
|
||||
type,
|
||||
value: val,
|
||||
draw: function (ctx, node, widgetWidth, widgetY, height) {
|
||||
const [cw, ch] = this.computeSize(widgetWidth);
|
||||
offsetDOMWidget(this, ctx, node, widgetWidth, widgetY, ch);
|
||||
},
|
||||
computeSize: function (_) {
|
||||
const ratio = this.inputRatio || 1;
|
||||
const width = Math.max(220, this.parent.size[0]);
|
||||
return [width, width / ratio + 10];
|
||||
},
|
||||
onRemoved: function () {
|
||||
if (this.inputEl) {
|
||||
this.inputEl.remove();
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
w.inputEl = document.createElement(type === "video" ? "video" : "img");
|
||||
w.inputEl.src = w.value;
|
||||
if (type === "video") {
|
||||
w.inputEl.setAttribute("type", "video/webm");
|
||||
w.inputEl.autoplay = true;
|
||||
w.inputEl.loop = true;
|
||||
w.inputEl.controls = false;
|
||||
}
|
||||
w.inputEl.onload = function () {
|
||||
w.inputRatio = w.inputEl.naturalWidth / w.inputEl.naturalHeight;
|
||||
callback?.();
|
||||
};
|
||||
document.body.appendChild(w.inputEl);
|
||||
return w;
|
||||
};
|
||||
|
||||
const videoPreview = {
|
||||
app.registerExtension({
|
||||
name: "AnimateDiff.VideoPreview",
|
||||
async beforeRegisterNodeDef(nodeType, nodeData, app) {
|
||||
const onExecuted = nodeType.prototype.onExecuted;
|
||||
nodeType.prototype.onExecuted = function (message) {
|
||||
const r = onExecuted ? onExecuted.apply(this, message) : undefined;
|
||||
|
||||
if (message?.videos) {
|
||||
this.videos = message.videos;
|
||||
}
|
||||
|
||||
return r;
|
||||
};
|
||||
|
||||
const onDrawBackground = nodeType.prototype.onDrawBackground;
|
||||
nodeType.prototype.onDrawBackground = function (ctx) {
|
||||
const r = onDrawBackground ? onDrawBackground.apply(this, arguments) : undefined;
|
||||
const node = this;
|
||||
const prefix = "ad_video_preview_";
|
||||
|
||||
if (node.videos_rendered === node.videos) {
|
||||
return r;
|
||||
}
|
||||
|
||||
if (node.widgets) {
|
||||
const pos = node.widgets.findIndex((w) => w.name === `${prefix}_0`);
|
||||
if (pos !== -1) {
|
||||
for (let i = pos; i < node.widgets.length; i++) {
|
||||
node.widgets[i].onRemoved?.();
|
||||
}
|
||||
node.widgets.length = pos;
|
||||
}
|
||||
}
|
||||
if (node.videos) {
|
||||
node.videos.forEach((params, i) => {
|
||||
const previewUrl = api.apiURL(
|
||||
"/view?" + new URLSearchParams(params).toString()
|
||||
);
|
||||
const w = node.addCustomWidget(
|
||||
CreatePreviewElement(
|
||||
`${prefix}_${i}`,
|
||||
previewUrl,
|
||||
params.format || "image/gif",
|
||||
node.computeSizeKeepWidth.bind(node)
|
||||
)
|
||||
);
|
||||
w.parent = node;
|
||||
});
|
||||
node.videos_rendered = node.videos;
|
||||
}
|
||||
|
||||
return r;
|
||||
};
|
||||
|
||||
const onRemoved = nodeType.prototype.onRemoved;
|
||||
nodeType.prototype.onRemoved = function () {
|
||||
cleanupNode(this);
|
||||
return onRemoved ? onRemoved.apply(this, arguments) : undefined;
|
||||
};
|
||||
|
||||
nodeType.prototype.computeSizeKeepWidth = function () {
|
||||
this.setSize([
|
||||
this.size[0],
|
||||
this.computeSize([this.size[0], this.size[1]])[1],
|
||||
]);
|
||||
};
|
||||
init() {
|
||||
$el('style', {
|
||||
textContent: style,
|
||||
parent: document.head,
|
||||
});
|
||||
},
|
||||
};
|
||||
async beforeRegisterNodeDef(nodeType, nodeData) {
|
||||
if (nodeData.name !== "AnimateDiffCombine") {
|
||||
return;
|
||||
}
|
||||
|
||||
app.registerExtension(videoPreview);
|
||||
addVideoPreview(nodeType);
|
||||
},
|
||||
});
|
||||
|
||||
+71
-169
@@ -1,188 +1,90 @@
|
||||
import { app } from "../../../scripts/app.js";
|
||||
import { api } from "../../../scripts/api.js";
|
||||
import { ComfyWidgets } from "../../../scripts/widgets.js";
|
||||
|
||||
const supportedVideoTypes = [
|
||||
"image/gif",
|
||||
"video/webm",
|
||||
"video/mp4",
|
||||
"video/mov",
|
||||
];
|
||||
import {
|
||||
chainCallback,
|
||||
addVideoPreview,
|
||||
} from "./vid_preview.js";
|
||||
|
||||
const VIDEOUPLOAD = (node, inputName, inputData, app) => {
|
||||
const previewWidget = "ad_video_preview";
|
||||
const videoWidget = node.widgets.find((w) => w.name === "video");
|
||||
let uploadWidget;
|
||||
async function uploadFile(file) {
|
||||
try {
|
||||
// Wrap file in formdata so it includes filename
|
||||
const body = new FormData();
|
||||
const new_file = new File([file], file.name, {
|
||||
type: file.type,
|
||||
lastModified: file.lastModified,
|
||||
});
|
||||
body.append("image", new_file);
|
||||
body.append("subfolder", "video");
|
||||
const resp = await api.fetchApi("/upload/image", {
|
||||
method: "POST",
|
||||
body,
|
||||
});
|
||||
|
||||
const showVideo = (name) => {
|
||||
let folder_separator = name.lastIndexOf("/");
|
||||
let subfolder = "";
|
||||
if (folder_separator > -1) {
|
||||
subfolder = name.substring(0, folder_separator);
|
||||
name = name.substring(folder_separator + 1);
|
||||
}
|
||||
const ext = name.substring(name.lastIndexOf(".") + 1);
|
||||
const format = supportedVideoTypes.find((t) => t.endsWith(ext));
|
||||
node.videos = [
|
||||
{
|
||||
filename: name,
|
||||
type: "input",
|
||||
subfolder: subfolder,
|
||||
format,
|
||||
},
|
||||
];
|
||||
};
|
||||
|
||||
var default_value = videoWidget.value;
|
||||
Object.defineProperty(videoWidget, "value", {
|
||||
set: function (value) {
|
||||
this._real_value = value;
|
||||
},
|
||||
|
||||
get: function () {
|
||||
let value = "";
|
||||
if (this._real_value) {
|
||||
value = this._real_value;
|
||||
} else {
|
||||
return default_value;
|
||||
}
|
||||
|
||||
if (value.filename) {
|
||||
let real_value = value;
|
||||
value = "";
|
||||
if (real_value.subfolder) {
|
||||
value = real_value.subfolder + "/";
|
||||
}
|
||||
|
||||
value += real_value.filename;
|
||||
|
||||
if (real_value.type && real_value.type !== "input")
|
||||
value += ` [${real_value.type}]`;
|
||||
}
|
||||
return value;
|
||||
},
|
||||
});
|
||||
|
||||
// Add our own callback to the combo widget to render an image when it changes
|
||||
const cb = node.callback;
|
||||
videoWidget.callback = function () {
|
||||
showVideo(videoWidget.value);
|
||||
if (cb) {
|
||||
return cb.apply(this, arguments);
|
||||
}
|
||||
};
|
||||
|
||||
// On load if we have a value then render the image
|
||||
// The value isnt set immediately so we need to wait a moment
|
||||
// No change callbacks seem to be fired on initial setting of the value
|
||||
requestAnimationFrame(() => {
|
||||
if (videoWidget.value) {
|
||||
showVideo(videoWidget.value);
|
||||
}
|
||||
});
|
||||
|
||||
async function uploadFile(file, updateNode, pasted = false) {
|
||||
try {
|
||||
// Wrap file in formdata so it includes filename
|
||||
const body = new FormData();
|
||||
body.append("image", file);
|
||||
body.append("subfolder", "video");
|
||||
const resp = await api.fetchApi("/upload/image", {
|
||||
method: "POST",
|
||||
body,
|
||||
});
|
||||
|
||||
if (resp.status === 200) {
|
||||
const data = await resp.json();
|
||||
// Add the file to the dropdown list and update the widget value
|
||||
let path = data.name;
|
||||
if (data.subfolder) path = data.subfolder + "/" + path;
|
||||
|
||||
if (!videoWidget.options.values.includes(path)) {
|
||||
videoWidget.options.values.push(path);
|
||||
}
|
||||
|
||||
if (updateNode) {
|
||||
showVideo(path);
|
||||
videoWidget.value = path;
|
||||
}
|
||||
} else {
|
||||
alert(resp.status + " - " + resp.statusText);
|
||||
}
|
||||
} catch (error) {
|
||||
alert(error);
|
||||
if (resp.status === 200 || resp.status === 201) {
|
||||
return resp.json();
|
||||
} else {
|
||||
alert(`Upload failed: ${resp.statusText}`);
|
||||
}
|
||||
} catch (error) {
|
||||
alert(`Upload failed: ${error}`);
|
||||
}
|
||||
}
|
||||
|
||||
const fileInput = document.createElement("input");
|
||||
Object.assign(fileInput, {
|
||||
type: "file",
|
||||
accept: supportedVideoTypes.join(","),
|
||||
style: "display: none",
|
||||
onchange: async () => {
|
||||
if (fileInput.files.length) {
|
||||
await uploadFile(fileInput.files[0], true);
|
||||
function addUploadWidget(nodeType, widgetName) {
|
||||
chainCallback(nodeType.prototype, "onNodeCreated", function () {
|
||||
const pathWidget = this.widgets.find((w) => w.name === widgetName);
|
||||
if (pathWidget.element) {
|
||||
pathWidget.options.getMinHeight = () => 50;
|
||||
pathWidget.options.getMaxHeight = () => 150;
|
||||
}
|
||||
|
||||
const fileInput = document.createElement("input");
|
||||
chainCallback(this, "onRemoved", () => {
|
||||
fileInput?.remove();
|
||||
});
|
||||
|
||||
Object.assign(fileInput, {
|
||||
type: "file",
|
||||
accept: "video/webm,video/mp4,video/mkv,image/gif,image/webp",
|
||||
style: "display: none",
|
||||
onchange: async () => {
|
||||
if (fileInput.files.length) {
|
||||
const params = await uploadFile(fileInput.files[0]);
|
||||
if (!params) {
|
||||
// upload failed and file can not be added to options
|
||||
return;
|
||||
}
|
||||
|
||||
fileInput.value = "";
|
||||
const filename = [params.subfolder, params.name || params.filename].filter(Boolean).join('/')
|
||||
pathWidget.value = filename;
|
||||
pathWidget.options.values.push(filename);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
document.body.append(fileInput);
|
||||
let uploadWidget = this.addWidget(
|
||||
"button",
|
||||
"choose video to upload",
|
||||
"image",
|
||||
() => {
|
||||
app.canvas.node_widget = null;
|
||||
fileInput.click();
|
||||
}
|
||||
},
|
||||
);
|
||||
uploadWidget.options.serialize = false;
|
||||
});
|
||||
document.body.append(fileInput);
|
||||
|
||||
// Create the button widget for selecting the files
|
||||
uploadWidget = node.addWidget(
|
||||
"button",
|
||||
"choose file to upload",
|
||||
"image",
|
||||
() => {
|
||||
fileInput.click();
|
||||
}
|
||||
);
|
||||
uploadWidget.serialize = false;
|
||||
|
||||
// Add handler to check if an image is being dragged over our node
|
||||
node.onDragOver = function (e) {
|
||||
if (e.dataTransfer && e.dataTransfer.items) {
|
||||
const image = [...e.dataTransfer.items].find((f) => f.kind === "file");
|
||||
return !!image;
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
||||
|
||||
// On drop upload files
|
||||
node.onDragDrop = function (e) {
|
||||
console.log("onDragDrop called");
|
||||
let handled = false;
|
||||
for (const file of e.dataTransfer.files) {
|
||||
if (file.type.startsWith("image/")) {
|
||||
uploadFile(file, !handled); // Dont await these, any order is fine, only update on first one
|
||||
handled = true;
|
||||
}
|
||||
}
|
||||
|
||||
return handled;
|
||||
};
|
||||
|
||||
node.pasteFile = function (file) {
|
||||
if (supportedVideoTypes.indexOf(file.type) > -1) {
|
||||
const is_pasted =
|
||||
file.name === "image.png" && file.lastModified - Date.now() < 2000;
|
||||
uploadFile(file, true, is_pasted);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
return { widget: uploadWidget };
|
||||
};
|
||||
|
||||
ComfyWidgets["VIDEOUPLOAD"] = VIDEOUPLOAD;
|
||||
}
|
||||
|
||||
// Adds an upload button to the nodes
|
||||
app.registerExtension({
|
||||
name: "AnimateDiff.UploadVideo",
|
||||
async beforeRegisterNodeDef(nodeType, nodeData, app) {
|
||||
if (nodeData?.input?.required?.video?.[1]?.video_upload === true) {
|
||||
nodeData.input.required.upload = ["VIDEOUPLOAD"];
|
||||
addUploadWidget(nodeType, 'video');
|
||||
addVideoPreview(nodeType, { comboWidget: 'video' });
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user