Compare commits

...
Author SHA1 Message Date
nick b3df94d1af update: don't randomize noise_seed if it's an input from another node 2025-02-24 09:44:59 -08:00
karrix 26b149553b tweak 2025-02-19 05:13:56 +08:00
karrix 17683d353c Revert "add: return output id"
This reverts commit 7552353e30.
2025-02-19 04:53:07 +08:00
karrix 7552353e30 add: return output id 2025-02-19 04:48:50 +08:00
karrix d619ad7f3b tweak 2025-02-19 04:34:26 +08:00
karrix f0ed0ad8f7 feat: output image id 2025-02-19 03:52:21 +08:00
BennyKok 7fce0b4976 Update README.md 2025-02-15 16:52:50 +08:00
ImpactFrames 0e218752ca Add external_exr.py (#79)
* Create external_exr.py

adds a node for loading exr images from url

* Update custom_routes.py

Adds EXR to the custom routes
2025-02-14 11:13:35 +08:00
bennykok 4073a43d3d use torch audio 2025-02-07 23:14:16 +08:00
bennykok 3d6a554f7f feat: add external audio node based on VHS node 2025-02-07 21:42:44 +08:00
KarrixLee ce939fbe1b add: gpu in info (#78) 2025-02-06 15:41:56 +08:00
bennykok 48f5ce15d7 fix: fallback to default api runs 2025-02-05 17:58:57 +08:00
karrix 9512437573 feat: send back event if the graph is loading properly 2025-02-05 14:41:35 +08:00
bennykok 649e431227 feat: configure_menu_buttons 2025-01-23 13:44:31 +08:00
EmmanuelMr18 411db66d81 Revert "chore: refresh models when getting object_info"
This reverts commit 67f25b2353.
2025-01-20 01:52:52 -05:00
Emmanuel Morales 67f25b2353 chore: refresh models when getting object_info
This is a WIP that will be used to refresh the models when execution comfyUI without having to stop the server and start a new one
2025-01-19 17:26:41 -06:00
bennykok ce3b0dbe84 chore: log prompt_id on start 2025-01-19 12:39:24 +08:00
bennykok fc36a8ad0f feat: add output image node 2025-01-19 12:39:06 +08:00
Robin Huangandsnomiao 638e625d72 chore(licence-update): Update PyProject Toml - License (#77)
Co-authored-by: snomiao <snomiao+comfy-pr@gmail.com>
2025-01-10 15:44:27 +08:00
EmmanuelMr18 230cee40d2 fix: add container to the buttons injected into the right menu 2025-01-10 01:08:42 -06:00
EmmanuelMr18 73853a60ff feat: inject buttons in the right position of the comfyui menu 2025-01-07 23:49:03 -06:00
bennykok 413115571b chore: add event for updating widget 2025-01-07 21:36:12 +08:00
bennykok bf00580562 feat: update external image node to have default value 2025-01-07 21:03:52 +08:00
bennykok 6ed468d7d4 feat: drag drop proxy + inject button to toolbar 2025-01-06 13:01:39 +08:00
bennykok 5423b4ee6f fix: simply js import 2025-01-05 14:00:42 +08:00
Emmanuel Morales 2c1656756d fix(updates): make updates async to avoid blocking execution (#75)
I tracked the time and takes ~200ms everytime that we send the "Executing <NODE NAME> n%".
So this means that if you have 10 custom nodes we are adding 2 extra seconds to the execution.
200 * 10 = 2,000.
Some workflows are more complext and have more custom nodes, so this only keeps increasing.
2025-01-03 16:25:04 +08:00
12 changed files with 834 additions and 126 deletions
+2 -1
View File
@@ -1,2 +1,3 @@
__pycache__
.DS_Store
.DS_Store
file-hash-cache.json
+3
View File
@@ -2,6 +2,9 @@
Open source comfyui deployment platform, a `vercel` for generative workflow infra. (serverless hosted gpu with vertical intergation with comfyui)
> [!NOTE]
> Im looking for creative hacker to join ComfyDeploy's core team! DM me on [twitter](https://x.com/BennyKokMusic)
Join [Discord](https://discord.gg/EEYcQmdYZw) to chat more or visit [Comfy Deploy](https://comfydeploy.com/) to get started!
Check out our latest [nextjs starter kit](https://github.com/BennyKok/comfyui-deploy-next-example) with Comfy Deploy
+57
View File
@@ -0,0 +1,57 @@
import os
import io
import torchaudio
from folder_paths import get_annotated_filepath
class ComfyUIDeployExternalAudio:
RETURN_TYPES = ("AUDIO",)
RETURN_NAMES = ("audio",)
FUNCTION = "load_audio"
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"input_id": (
"STRING",
{"multiline": False, "default": "input_audio"},
),
"audio_file": ("STRING", {"default": ""}),
},
"optional": {
"default_value": ("AUDIO",),
"display_name": (
"STRING",
{"multiline": False, "default": ""},
),
"description": (
"STRING",
{"multiline": False, "default": ""},
),
}
}
@classmethod
def VALIDATE_INPUTS(s, audio_file, **kwargs):
return True
def load_audio(self, input_id, audio_file, default_value=None, display_name=None, description=None):
if audio_file and audio_file != "":
if audio_file.startswith(('http://', 'https://')):
# Handle URL input
import requests
response = requests.get(audio_file)
audio_data = io.BytesIO(response.content)
waveform, sample_rate = torchaudio.load(audio_data)
else:
# Handle local file
audio_path = get_annotated_filepath(audio_file)
waveform, sample_rate = torchaudio.load(audio_path)
audio = {"waveform": waveform.unsqueeze(0), "sample_rate": sample_rate}
return (audio,)
else:
return (default_value,)
NODE_CLASS_MAPPINGS = {"ComfyUIDeployExternalAudio": ComfyUIDeployExternalAudio}
NODE_DISPLAY_NAME_MAPPINGS = {"ComfyUIDeployExternalAudio": "External Audio (ComfyUI Deploy)"}
+109
View File
@@ -0,0 +1,109 @@
import os
import io
import cv2 as cv
import numpy as np
import torch
import requests
from folder_paths import get_annotated_filepath
class ComfyUIDeployExternalEXR:
RETURN_TYPES = ("IMAGE", "MASK")
RETURN_NAMES = ("image", "mask")
FUNCTION = "load_exr"
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"input_id": (
"STRING",
{"multiline": False, "default": "input_exr"},
),
"exr_file": ("STRING", {"default": ""}),
"tonemap": (["linear", "sRGB", "Reinhard"], {"default": "sRGB"}),
},
"optional": {
"default_image": ("IMAGE",),
"default_mask": ("MASK",),
"display_name": (
"STRING",
{"multiline": False, "default": ""},
),
"description": (
"STRING",
{"multiline": False, "default": ""},
),
}
}
@classmethod
def VALIDATE_INPUTS(s, exr_file, **kwargs):
return True
def sRGBtoLinear(self, npArray):
less = npArray <= 0.0404482362771082
npArray[less] = npArray[less] / 12.92
npArray[~less] = np.power((npArray[~less] + 0.055) / 1.055, 2.4)
def linearToSRGB(self, npArray):
less = npArray <= 0.0031308
npArray[less] = npArray[less] * 12.92
npArray[~less] = np.power(npArray[~less], 1/2.4) * 1.055 - 0.055
def load_exr(self, input_id, exr_file, tonemap="sRGB",
default_image=None, default_mask=None,
display_name=None, description=None):
try:
if exr_file and exr_file != "":
if exr_file.startswith(('http://', 'https://')):
# Handle URL input
response = requests.get(exr_file)
# Write to temp buffer
buffer = io.BytesIO(response.content)
nparr = np.frombuffer(buffer.getvalue(), np.uint8)
image = cv.imdecode(nparr, cv.IMREAD_UNCHANGED).astype(np.float32)
else:
# Handle local file
exr_path = get_annotated_filepath(exr_file)
image = cv.imread(exr_path, cv.IMREAD_UNCHANGED).astype(np.float32)
if len(image.shape) == 2:
image = np.repeat(image[..., np.newaxis], 3, axis=2)
# Extract RGB and flip channels
rgb = np.flip(image[:,:,:3], 2).copy()
# Apply tonemapping
if tonemap == "sRGB":
self.linearToSRGB(rgb)
rgb = np.clip(rgb, 0, 1)
elif tonemap == "Reinhard":
rgb = np.clip(rgb, 0, None)
rgb = rgb / (rgb + 1)
self.linearToSRGB(rgb)
rgb = np.clip(rgb, 0, 1)
rgb = torch.unsqueeze(torch.from_numpy(rgb), 0)
# Handle alpha/mask
mask = torch.zeros((1, image.shape[0], image.shape[1]), dtype=torch.float32)
if image.shape[2] > 3:
mask[0] = torch.from_numpy(np.clip(image[:,:,3], 0, 1))
return (rgb, mask)
else:
# Return defaults if no file provided
return (default_image, default_mask)
except Exception as e:
print(f"Error loading EXR: {str(e)}")
# Return defaults on error
return (default_image, default_mask)
NODE_CLASS_MAPPINGS = {
"ComfyUIDeployExternalEXR": ComfyUIDeployExternalEXR
}
NODE_DISPLAY_NAME_MAPPINGS = {
"ComfyUIDeployExternalEXR": "External EXR (ComfyUI Deploy)"
}
+39 -26
View File
@@ -21,8 +21,9 @@ class ComfyUIDeployExternalImage:
),
"description": (
"STRING",
{"multiline": True, "default": ""},
{"multiline": False, "default": ""},
),
"default_value_url": ("STRING", {"image_preview": True, "default": ""}),
}
}
@@ -33,32 +34,44 @@ class ComfyUIDeployExternalImage:
CATEGORY = "image"
def run(self, input_id, default_value=None, display_name=None, description=None):
def run(self, input_id, default_value=None, display_name=None, description=None, default_value_url=None):
image = default_value
try:
if input_id.startswith('http'):
import requests
from io import BytesIO
print("Fetching image from url: ", input_id)
response = requests.get(input_id)
image = Image.open(BytesIO(response.content))
elif input_id.startswith('data:image/png;base64,') or input_id.startswith('data:image/jpeg;base64,') or input_id.startswith('data:image/jpg;base64,'):
import base64
from io import BytesIO
print("Decoding base64 image")
base64_image = input_id[input_id.find(",")+1:]
decoded_image = base64.b64decode(base64_image)
image = Image.open(BytesIO(decoded_image))
else:
raise ValueError("Invalid image url provided.")
image = ImageOps.exif_transpose(image)
image = image.convert("RGB")
image = np.array(image).astype(np.float32) / 255.0
image = torch.from_numpy(image)[None,]
return [image]
except:
return [image]
# Try both input_id and default_value_url
urls_to_try = [url for url in [input_id, default_value_url] if url]
print(default_value_url)
for url in urls_to_try:
try:
if url.startswith('http'):
import requests
from io import BytesIO
print(f"Fetching image from url: {url}")
response = requests.get(url)
image = Image.open(BytesIO(response.content))
break
elif url.startswith(('data:image/png;base64,', 'data:image/jpeg;base64,', 'data:image/jpg;base64,')):
import base64
from io import BytesIO
print("Decoding base64 image")
base64_image = url[url.find(",")+1:]
decoded_image = base64.b64decode(base64_image)
image = Image.open(BytesIO(decoded_image))
break
except:
continue
if image is not None:
try:
image = ImageOps.exif_transpose(image)
image = image.convert("RGB")
image = np.array(image).astype(np.float32) / 255.0
image = torch.from_numpy(image)[None,]
except:
pass
return [image]
NODE_CLASS_MAPPINGS = {"ComfyUIDeployExternalImage": ComfyUIDeployExternalImage}
+100
View File
@@ -0,0 +1,100 @@
import os
import json
import numpy as np
from PIL import Image
from PIL.PngImagePlugin import PngInfo
import folder_paths
class ComfyDeployOutputImage:
def __init__(self):
self.output_dir = folder_paths.get_output_directory()
self.type = "output"
self.prefix_append = ""
self.compress_level = 4
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"images": ("IMAGE", {"tooltip": "The images to save."}),
"filename_prefix": (
"STRING",
{
"default": "ComfyUI",
"tooltip": "The prefix for the file to save. This may include formatting information such as %date:yyyy-MM-dd% or %Empty Latent Image.width% to include values from nodes.",
},
),
"file_type": (["png", "jpg", "webp"], {"default": "webp"}),
"quality": ("INT", {"default": 80, "min": 1, "max": 100, "step": 1}),
"output_id": (
"STRING",
{"multiline": False, "default": "output_images"},
),
},
"hidden": {"prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO"},
}
RETURN_TYPES = ()
FUNCTION = "run"
OUTPUT_NODE = True
CATEGORY = "output"
DESCRIPTION = "Saves the input images to your ComfyUI output directory."
def run(
self,
images,
filename_prefix="ComfyUI",
file_type="png",
quality=80,
output_id="output_images",
prompt=None,
extra_pnginfo=None,
):
filename_prefix += self.prefix_append
full_output_folder, filename, counter, subfolder, filename_prefix = (
folder_paths.get_save_image_path(
filename_prefix, self.output_dir, images[0].shape[1], images[0].shape[0]
)
)
results = list()
for batch_number, image in enumerate(images):
i = 255.0 * image.cpu().numpy()
img = Image.fromarray(np.clip(i, 0, 255).astype(np.uint8))
metadata = PngInfo()
if prompt is not None:
metadata.add_text("prompt", json.dumps(prompt))
if extra_pnginfo is not None:
for x in extra_pnginfo:
metadata.add_text(x, json.dumps(extra_pnginfo[x]))
filename_with_batch_num = filename.replace("%batch_num%", str(batch_number))
file = f"{filename_with_batch_num}_{counter:05}_.{file_type}"
file_path = os.path.join(full_output_folder, file)
if file_type == "png":
img.save(
file_path, pnginfo=metadata, compress_level=self.compress_level
)
elif file_type == "jpg":
img.save(file_path, quality=quality, optimize=True)
elif file_type == "webp":
img.save(file_path, quality=quality)
results.append(
{
"filename": file,
"subfolder": subfolder,
"type": self.type,
"output_id": output_id,
}
)
counter += 1
return {"ui": {"images": results}}
NODE_CLASS_MAPPINGS = {"ComfyDeployOutputImage": ComfyDeployOutputImage}
NODE_DISPLAY_NAME_MAPPINGS = {"ComfyDeployOutputImage": "Image Output (ComfyDeploy)"}
+90 -62
View File
@@ -30,6 +30,7 @@ from model_management import get_torch_device
import torch
import psutil
from collections import OrderedDict
# Global session
client_session = None
@@ -302,6 +303,7 @@ def apply_random_seed_to_workflow(workflow_api):
for key in workflow_api:
if "inputs" in workflow_api[key]:
if "seed" in workflow_api[key]["inputs"]:
# If seed is a list, it's an input from another node (generally `external number int`)
if isinstance(workflow_api[key]["inputs"]["seed"], list):
continue
if workflow_api[key]["class_type"] == "PromptExpansion":
@@ -316,6 +318,9 @@ def apply_random_seed_to_workflow(workflow_api):
)
if "noise_seed" in workflow_api[key]["inputs"]:
# If noise_seed is a list, it's an input from another node (generally `external number int`)
if isinstance(workflow_api[key]["inputs"]["noise_seed"], list):
continue
if workflow_api[key]["class_type"] == "RandomNoise":
workflow_api[key]["inputs"]["noise_seed"] = randomSeed()
logger.info(
@@ -386,6 +391,12 @@ def apply_inputs_to_workflow(workflow_api: Any, inputs: Any, sid: str = None):
if value["class_type"] == "ComfyUIDeployExternalFaceModel":
value["inputs"]["face_model_url"] = new_value
if value["class_type"] == "ComfyUIDeployExternalAudio":
value["inputs"]["audio_file"] = new_value
if value["class_type"] == "ComfyUIDeployExternalEXR":
value["inputs"]["exr_file"] = new_value
def send_prompt(sid: str, inputs: StreamingPrompt):
# workflow_api = inputs.workflow_api
@@ -1074,7 +1085,7 @@ async def send(event, data, sid=None):
@server.PromptServer.instance.routes.post("/comfydeploy/{tail:.*}")
async def proxy_to_comfydeploy(request):
# Get the base URL
base_url = f'https://www.comfydeploy.com/{request.match_info["tail"]}'
base_url = f"https://www.comfydeploy.com/{request.match_info['tail']}"
# Get all query parameters
query_params = request.query_string
@@ -1125,14 +1136,15 @@ async def proxy_to_comfydeploy(request):
prompt_server = server.PromptServer.instance
NODE_EXECUTION_TIMES = {} # New dictionary to store node execution times
NODE_EXECUTION_TIMES = {} # New dictionary to store node execution times
CURRENT_START_EXECUTION_DATA = None
def get_peak_memory():
device = get_torch_device()
if device.type == 'cuda':
if device.type == "cuda":
return torch.cuda.max_memory_allocated(device)
elif device.type == 'mps':
elif device.type == "mps":
# Return system memory usage for MPS devices
return psutil.Process().memory_info().rss
return 0
@@ -1140,7 +1152,7 @@ def get_peak_memory():
def reset_peak_memory_record():
device = get_torch_device()
if device.type == 'cuda':
if device.type == "cuda":
torch.cuda.reset_max_memory_allocated(device)
# MPS doesn't need reset as we're not tracking its memory
@@ -1161,7 +1173,7 @@ def handle_execute(class_type, last_node_id, prompt_id, server, unique_id):
NODE_EXECUTION_TIMES[unique_id] = {
"time": execution_time,
"class_type": class_type,
"vram_used": vram_used
"vram_used": vram_used,
}
# print(f"#{unique_id} [{class_type}]: {execution_time:.2f}s - vram {vram_used}b")
@@ -1201,31 +1213,37 @@ try:
except Exception as e:
pass
def format_table(headers, data):
# Calculate column widths
widths = [len(h) for h in headers]
for row in data:
for i, cell in enumerate(row):
widths[i] = max(widths[i], len(str(cell)))
# Create separator line
separator = '+' + '+'.join('-' * (w + 2) for w in widths) + '+'
separator = "+" + "+".join("-" * (w + 2) for w in widths) + "+"
# Format header
result = [separator]
header_row = '|' + '|'.join(f' {h:<{w}} ' for w, h in zip(widths, headers)) + '|'
header_row = "|" + "|".join(f" {h:<{w}} " for w, h in zip(widths, headers)) + "|"
result.append(header_row)
result.append(separator)
# Format data rows
for row in data:
data_row = '|' + '|'.join(f' {str(cell):<{w}} ' for w, cell in zip(widths, row)) + '|'
data_row = (
"|" + "|".join(f" {str(cell):<{w}} " for w, cell in zip(widths, row)) + "|"
)
result.append(data_row)
result.append(separator)
return '\n'.join(result)
return "\n".join(result)
origin_func = server.PromptServer.send_sync
def swizzle_send_sync(self, event, data, sid=None):
# print(f"swizzle_send_sync, event: {event}, data: {data}")
global CURRENT_START_EXECUTION_DATA
@@ -1251,10 +1269,12 @@ def swizzle_send_sync(self, event, data, sid=None):
get_peak_memory()
)
server.PromptServer.send_sync = swizzle_send_sync
send_json = prompt_server.send_json
async def send_json_override(self, event, data, sid=None):
# logger.info("INTERNAL:", event, data, sid)
prompt_id = data.get("prompt_id")
@@ -1279,10 +1299,11 @@ async def send_json_override(self, event, data, sid=None):
if event == "execution_start":
if prompt_id in prompt_metadata:
prompt_metadata[prompt_id].start_time = time.perf_counter()
await update_run(prompt_id, Status.RUNNING)
logger.info("Executing prompt: " + prompt_id)
asyncio.create_task(update_run(prompt_id, Status.RUNNING))
if event == "executing" and data and CURRENT_START_EXECUTION_DATA:
if data.get("node") is None:
start_perf_time = CURRENT_START_EXECUTION_DATA.get("start_perf_time")
@@ -1290,43 +1311,44 @@ async def send_json_override(self, event, data, sid=None):
if start_perf_time is not None:
execution_time = time.perf_counter() - start_perf_time
new_data["execution_time"] = int(execution_time * 1000)
# Replace the print statements with tabulate
headers = ["Node ID", "Type", "Time (s)", "VRAM (GB)"]
table_data = []
node_execution_array = [] # New array to store execution data
for node_id, node_data in NODE_EXECUTION_TIMES.items():
vram_gb = node_data['vram_used'] / (1024**3) # Convert bytes to GB
table_data.append([
f"#{node_id}",
node_data['class_type'],
f"{node_data['time']:.2f}",
f"{vram_gb:.2f}"
])
vram_gb = node_data["vram_used"] / (1024**3) # Convert bytes to GB
table_data.append(
[
f"#{node_id}",
node_data["class_type"],
f"{node_data['time']:.2f}",
f"{vram_gb:.2f}",
]
)
# Add to our new array format
node_execution_array.append({
"id": node_id,
**node_data,
})
node_execution_array.append(
{
"id": node_id,
**node_data,
}
)
# Add total execution time as the last row
table_data.append([
"TOTAL",
"-",
f"{execution_time:.2f}",
"-"
])
table_data.append(["TOTAL", "-", f"{execution_time:.2f}", "-"])
prompt_id = data.get("prompt_id")
await update_run_with_output(
prompt_id,
node_execution_array, # Send the array instead of the OrderedDict
asyncio.create_task(
update_run_with_output(
prompt_id,
node_execution_array, # Send the array instead of the OrderedDict
)
)
print(node_execution_array)
# print("\n=== Node Execution Times ===")
logger.info("Printing Node Execution Times")
logger.info(format_table(headers, table_data))
@@ -1342,10 +1364,12 @@ async def send_json_override(self, event, data, sid=None):
if prompt_metadata[prompt_id].start_time is not None:
elapsed_time = current_time - prompt_metadata[prompt_id].start_time
logger.info(f"Elapsed time: {elapsed_time} seconds")
await send(
"elapsed_time",
{"prompt_id": prompt_id, "elapsed_time": elapsed_time},
sid=sid,
asyncio.create_task(
send(
"elapsed_time",
{"prompt_id": prompt_id, "elapsed_time": elapsed_time},
sid=sid,
)
)
if event == "executing" and data.get("node") is not None:
@@ -1370,17 +1394,21 @@ async def send_json_override(self, event, data, sid=None):
prompt_metadata[prompt_id].last_updated_node = node
class_type = prompt_metadata[prompt_id].workflow_api[node]["class_type"]
logger.info(f"At: {round(calculated_progress * 100)}% - {class_type}")
await send(
"live_status",
{
"prompt_id": prompt_id,
"current_node": class_type,
"progress": calculated_progress,
},
sid=sid,
asyncio.create_task(
send(
"live_status",
{
"prompt_id": prompt_id,
"current_node": class_type,
"progress": calculated_progress,
},
sid=sid,
)
)
await update_run_live_status(
prompt_id, "Executing " + class_type, calculated_progress
asyncio.create_task(
update_run_live_status(
prompt_id, "Executing " + class_type, calculated_progress
)
)
if event == "execution_cached" and data.get("nodes") is not None:
@@ -1897,9 +1925,9 @@ async def upload_in_background(
# await handle_upload(prompt_id, data, 'files', "content_type", "image/png")
# await handle_upload(prompt_id, data, 'gifs', "format", "image/gif")
# await handle_upload(prompt_id, data, 'mesh', "format", "application/octet-stream")
file_upload_endpoint = prompt_metadata[prompt_id].file_upload_endpoint
if file_upload_endpoint is not None and file_upload_endpoint != "":
upload_tasks = [
handle_upload(prompt_id, data, "images", "content_type", "image/png"),
@@ -1913,7 +1941,7 @@ async def upload_in_background(
await asyncio.gather(*upload_tasks)
else:
print("No file upload endpoint, skipping file upload")
status_endpoint = prompt_metadata[prompt_id].status_endpoint
token = prompt_metadata[prompt_id].token
gpu_event_id = prompt_metadata[prompt_id].gpu_event_id or None
+1 -1
View File
@@ -2,7 +2,7 @@
name = "comfyui-deploy"
description = "Open source comfyui deployment platform, a vercel for generative workflow infra."
version = "1.1.0"
license = "LICENSE"
license = { file = "LICENSE" }
dependencies = ["aiofiles", "pydantic", "opencv-python", "imageio-ffmpeg"]
[project.urls]
-4
View File
@@ -1,4 +0,0 @@
/** @typedef {import('../../../web/scripts/api.js').api} API*/
import { api as _api } from '../../scripts/api.js';
/** @type {API} */
export const api = _api;
-4
View File
@@ -1,4 +0,0 @@
/** @typedef {import('../../../web/scripts/app.js').ComfyApp} ComfyApp*/
import { app as _app } from '../../scripts/app.js';
/** @type {ComfyApp} */
export const app = _app;
+433 -10
View File
@@ -1,8 +1,11 @@
import { app } from "./app.js";
import { api } from "./api.js";
import { ComfyWidgets, LGraphNode } from "./widgets.js";
import { app } from "../../scripts/app.js";
import { api } from "../../scripts/api.js";
// import { LGraphNode } from "../../scripts/widgets.js";
LGraphNode = LiteGraph.LGraphNode;
import { ComfyDialog, $el } from "../../scripts/ui.js";
import { generateDependencyGraph } from "https://esm.sh/comfyui-json@0.1.25";
import { ComfyDeploy } from "https://esm.sh/comfydeploy@0.0.19-beta.30";
import { ComfyDeploy } from "https://esm.sh/comfydeploy@2.0.0-beta.69";
const styles = `
.comfydeploy-menu-item {
@@ -47,6 +50,14 @@ function sendEventToCD(event, data) {
window.parent.postMessage(JSON.stringify(message), "*");
}
function sendDirectEventToCD(event, data) {
const message = {
type: event,
data: data,
};
window.parent.postMessage(message, "*");
}
function dispatchAPIEventData(data) {
const msg = JSON.parse(data);
@@ -483,6 +494,13 @@ const ext = {
return r;
};
if (
nodeData?.input?.optional?.default_value_url?.[1]?.image_preview === true
) {
nodeData.input.optional.default_value_url = ["IMAGEPREVIEW"];
console.log(nodeData.input.optional.default_value_url);
}
// const origonNodeCreated = nodeType.prototype.onNodeCreated;
// nodeType.prototype.onNodeCreated = function () {
// const r = origonNodeCreated
@@ -609,6 +627,78 @@ const ext = {
ComfyDeploy.category = "deploy";
},
getCustomWidgets() {
return {
IMAGEPREVIEW(node, inputName, inputData) {
// Find or create the URL input widget
const urlWidget = node.addWidget(
"string",
inputName,
/* value=*/ "",
() => {},
{ serialize: true },
);
const buttonWidget = node.addWidget(
"button",
"Open Assets Browser",
/* value=*/ "",
() => {
sendEventToCD("assets", {
node: node.id,
inputName: inputName,
});
// console.log("load image");
},
{ serialize: false },
);
console.log(node.widgets);
console.log("urlWidget", urlWidget);
// Add image preview functionality
function showImage(url) {
const img = new Image();
img.onload = () => {
node.imgs = [img];
app.graph.setDirtyCanvas(true);
node.setSizeForImage?.();
};
img.onerror = () => {
node.imgs = [];
app.graph.setDirtyCanvas(true);
};
img.src = url;
}
// Set up URL widget value handling
let default_value = urlWidget.value;
Object.defineProperty(urlWidget, "value", {
set: function (value) {
this._real_value = value;
// Preview image when URL changes
if (value) {
showImage(value);
}
},
get: function () {
return this._real_value || default_value;
},
});
// Show initial image if URL exists
requestAnimationFrame(() => {
if (urlWidget.value) {
showImage(urlWidget.value);
}
});
return { widget: urlWidget };
},
};
},
async setup() {
// const graphCanvas = document.getElementById("graph-canvas");
@@ -636,6 +726,7 @@ const ext = {
}
console.log("loadGraphData");
app.loadGraphData(comfyUIWorkflow);
sendEventToCD("graph_loaded");
}
} else if (message.type === "deploy") {
// deployWorkflow();
@@ -650,11 +741,35 @@ const ext = {
console.warn("api.handlePromptGenerated is not a function");
}
sendEventToCD("cd_plugin_onQueuePrompt", prompt);
} else if (message.type === "configure_queue_buttons") {
addQueueButtons(message.data);
} else if (message.type === "configure_menu_right_buttons") {
addMenuRightButtons(message.data);
} else if (message.type === "configure_menu_buttons") {
addMenuButtons(message.data);
} else if (message.type === "get_prompt") {
const prompt = await app.graphToPrompt();
sendEventToCD("cd_plugin_onGetPrompt", prompt);
} else if (message.type === "event") {
dispatchAPIEventData(message.data);
} else if (message.type === "update_widget") {
// New handler for updating widget values
const { nodeId, widgetName, value } = message.data;
const node = app.graph.getNodeById(nodeId);
if (!node) {
console.warn(`Node with ID ${nodeId} not found`);
return;
}
const widget = node.widgets?.find((w) => w.name === widgetName);
if (!widget) {
console.warn(`Widget ${widgetName} not found in node ${nodeId}`);
return;
}
widget.value = value;
app.graph.setDirtyCanvas(true);
} else if (message.type === "add_node") {
console.log("add node", message.data);
app.graph.beforeChange();
@@ -752,9 +867,9 @@ const ext = {
);
await app.ui.settings.setSettingValueAsync(
"Comfy.Sidebar.Location",
"right",
"left",
);
localStorage.setItem("Comfy.MenuPosition.Docked", "true");
// localStorage.setItem("Comfy.MenuPosition.Docked", "true");
console.log("native mode manmanman");
} catch (error) {
console.error("Error setting validation to false", error);
@@ -1287,8 +1402,6 @@ function addButton() {
app.registerExtension(ext);
import { ComfyDialog, $el } from "../../scripts/ui.js";
export class InfoDialog extends ComfyDialog {
constructor() {
super();
@@ -1759,7 +1872,7 @@ app.extensionManager.registerSidebarTab({
<div style="padding: 20px;">
<h3>Comfy Deploy</h3>
<div id="deploy-container" style="margin-bottom: 20px;"></div>
<div id="workflows-container">
<div id="workflows-container" style="display: none;">
<h4>Your Workflows</h4>
<div id="workflows-loading" style="display: flex; justify-content: center; align-items: center; height: 100px;">
${loadingIcon}
@@ -1859,10 +1972,16 @@ async function loadWorkflowApi(versionId) {
const orginal_fetch_api = api.fetchApi;
api.fetchApi = async (route, options) => {
console.log("Fetch API called with args:", route, options, ext.native_mode);
// console.log("Fetch API called with args:", route, options, ext.native_mode);
if (route.startsWith("/prompt") && ext.native_mode) {
const info = await getSelectedWorkflowInfo();
if (!info.workflow_id) {
console.log("No workflow id found, fallback to original fetch");
return await orginal_fetch_api.call(api, route, options);
}
console.log("info", info);
if (info) {
const body = JSON.parse(options.body);
@@ -1876,6 +1995,7 @@ api.fetchApi = async (route, options) => {
workflow_id: info.workflow_id,
native_run_api_endpoint: info.native_run_api_endpoint,
gpu_event_id: info.gpu_event_id,
gpu: info.gpu,
};
return await fetch("/comfyui-deploy/run", {
@@ -1891,3 +2011,306 @@ api.fetchApi = async (route, options) => {
return await orginal_fetch_api.call(api, route, options);
};
// Intercept window drag and drop events
const originalDropHandler = document.ondrop;
document.ondrop = async (e) => {
console.log("Drop event intercepted:", e);
// Prevent default browser behavior
e.preventDefault();
// Handle files if present
if (e.dataTransfer?.files?.length > 0) {
const files = Array.from(e.dataTransfer.files);
// Send file data to parent directly as JSON
sendDirectEventToCD("file_drop", {
files: files,
x: e.clientX,
y: e.clientY,
timestamp: Date.now(),
});
}
// Call original handler if exists
if (originalDropHandler) {
originalDropHandler(e);
}
};
const originalDragEnterHandler = document.ondragenter;
document.ondragenter = (e) => {
// Prevent default to allow drop
e.preventDefault();
// Send dragenter event to parent directly as JSON
sendDirectEventToCD("file_dragenter", {
x: e.clientX,
y: e.clientY,
timestamp: Date.now(),
});
if (originalDragEnterHandler) {
originalDragEnterHandler(e);
}
};
const originalDragLeaveHandler = document.ondragleave;
document.ondragleave = (e) => {
// Prevent default to allow drop
e.preventDefault();
// Send dragleave event to parent directly as JSON
sendDirectEventToCD("file_dragleave", {
x: e.clientX,
y: e.clientY,
timestamp: Date.now(),
});
if (originalDragLeaveHandler) {
originalDragLeaveHandler(e);
}
};
const originalDragOverHandler = document.ondragover;
document.ondragover = (e) => {
// Prevent default to allow drop
e.preventDefault();
// Send dragover event to parent directly as JSON
sendDirectEventToCD("file_dragover", {
x: e.clientX,
y: e.clientY,
timestamp: Date.now(),
});
if (originalDragOverHandler) {
originalDragOverHandler(e);
}
};
// Function to create a single button
function createQueueButton(config) {
const button = document.createElement("button");
button.id = `cd-button-${config.id}`;
button.className =
"p-button p-component p-button-icon-only p-button-secondary p-button-text";
button.innerHTML = `
<span class="p-button-icon pi ${config.icon}"></span>
<span class="p-button-label">&nbsp;</span>
`;
button.onclick = () => {
const eventData =
typeof config.eventData === "function"
? config.eventData()
: config.eventData || {};
sendEventToCD(config.event, eventData);
};
button.setAttribute("data-pd-tooltip", config.tooltip);
return button;
}
// Function to add buttons to queue group
function addQueueButtons(buttonConfigs = DEFAULT_BUTTONS) {
const queueButtonGroup = document.querySelector(".queue-button-group.flex");
if (!queueButtonGroup) return;
// Remove any existing CD buttons
const existingButtons =
queueButtonGroup.querySelectorAll('[id^="cd-button-"]');
existingButtons.forEach((button) => button.remove());
// Add new buttons
buttonConfigs.forEach((config) => {
const button = createQueueButton(config);
queueButtonGroup.appendChild(button);
});
}
// addMenuRightButtons([
// {
// id: "cd-button-save-image",
// icon: "pi-save",
// label: "Snapshot",
// tooltip: "Save the current image to your output directory.",
// event: "save_image",
// eventData: () => ({}),
// },
// ]);
// addMenuLeftButtons([
// {
// id: "cd-button-back",
// icon: `<svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
// <path d="M15 18L9 12L15 6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
// </svg>`,
// tooltip: "Go back to the previous page.",
// event: "back",
// eventData: () => ({}),
// },
// ]);
// addMenuButtons({
// containerSelector: "body > div.comfyui-body-top > div",
// buttonConfigs: [
// {
// id: "cd-button-workflow-1",
// icon: `<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="m16 3l4 4l-4 4m-6-4h10M8 13l-4 4l4 4m-4-4h9"/></svg>`,
// label: "Workflow",
// tooltip: "Go to Workflow 1",
// event: "workflow_1",
// // btnClasses: "",
// eventData: () => ({}),
// },
// {
// id: "cd-button-workflow-3",
// // icon: `<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="m16 3l4 4l-4 4m-6-4h10M8 13l-4 4l4 4m-4-4h9"/></svg>`,
// label: "v1",
// tooltip: "Go to Workflow 1",
// event: "workflow_1",
// // btnClasses: "",
// eventData: () => ({}),
// },
// {
// id: "cd-button-workflow-2",
// icon: `<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24"><g fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"><path d="M12 3v6"/><circle cx="12" cy="12" r="3"/><path d="M12 15v6"/></g></svg>`,
// label: "Commit",
// tooltip: "Commit the current workflow",
// event: "commit",
// style: {
// backgroundColor: "oklch(.476 .114 61.907)",
// },
// eventData: () => ({}),
// },
// ],
// buttonIdPrefix: "cd-button-workflow-",
// insertBefore:
// "body > div.comfyui-body-top > div > div.flex-grow.min-w-0.app-drag.h-full",
// // containerStyle: { order: "3" }
// });
// addMenuButtons({
// containerSelector:
// "body > div.comfyui-body-top > div > div.flex-grow.min-w-0.app-drag.h-full",
// clearContainer: true,
// buttonConfigs: [],
// buttonIdPrefix: "cd-button-p-",
// containerStyle: { order: "-1" },
// });
// Function to add buttons to a menu container
function addMenuButtons(options) {
const {
containerSelector,
buttonConfigs,
buttonIdPrefix = "cd-button-",
containerClass = "comfyui-button-group",
containerStyle = {},
clearContainer = false,
insertBefore = null, // New option to specify selector for insertion point
} = options;
const menuContainer = document.querySelector(containerSelector);
if (!menuContainer) return;
// Remove any existing CD buttons
const existingButtons = document.querySelectorAll(
`[id^="${buttonIdPrefix}"]`,
);
existingButtons.forEach((button) => button.remove());
const container = document.createElement("div");
container.className = containerClass;
// Apply container styles
Object.assign(container.style, containerStyle);
// Clear existing content if specified
if (clearContainer) {
menuContainer.innerHTML = "";
}
// Create and add buttons
buttonConfigs.forEach((config) => {
const button = createMenuButton({
...config,
idPrefix: buttonIdPrefix,
});
container.appendChild(button);
});
// Insert before specified element if provided, otherwise append
if (insertBefore) {
const targetElement = menuContainer.querySelector(insertBefore);
if (targetElement) {
menuContainer.insertBefore(container, targetElement);
} else {
menuContainer.appendChild(container);
}
} else {
menuContainer.appendChild(container);
}
}
function createMenuButton(config) {
const {
id,
icon,
label,
btnClasses = "",
tooltip,
event,
eventData,
idPrefix,
style = {},
} = config;
const button = document.createElement("button");
button.id = `${idPrefix}${id}`;
button.className = `comfyui-button ${btnClasses}`;
Object.assign(button.style, style);
// Only add icon if provided
const iconHtml = icon
? icon.startsWith("<svg")
? icon
: `<span class="p-button-icon pi ${icon}"></span>`
: "";
button.innerHTML = `
${iconHtml}
${label ? `<span class="p-button-label text-sm">${label}</span>` : ""}
`;
button.onclick = () => {
const data =
typeof eventData === "function" ? eventData() : eventData || {};
sendEventToCD(event, data);
};
if (tooltip) {
button.setAttribute("data-pd-tooltip", tooltip);
}
return button;
}
// Refactored menu button functions
function addMenuLeftButtons(buttonConfigs) {
addMenuButtons({
containerSelector: "body > div.comfyui-body-top > div",
buttonConfigs,
buttonIdPrefix: "cd-button-left-",
containerStyle: { order: "-1" },
});
}
function addMenuRightButtons(buttonConfigs) {
addMenuButtons({
containerSelector: ".comfyui-menu-right .flex",
buttonConfigs,
buttonIdPrefix: "cd-button-",
containerStyle: {},
});
}
-18
View File
@@ -1,18 +0,0 @@
// /** @typedef {import('../../../web/scripts/api.js').api} API*/
// import { api as _api } from "../../scripts/api.js";
// /** @type {API} */
// export const api = _api;
/** @typedef {typeof import('../../../web/scripts/widgets.js').ComfyWidgets} Widgets*/
import { ComfyWidgets as _ComfyWidgets } from "../../scripts/widgets.js";
/**
* @type {Widgets}
*/
export const ComfyWidgets = _ComfyWidgets;
// import { LGraphNode as _LGraphNode } from "../../types/litegraph.js";
/** @typedef {typeof import('../../../web/types/litegraph.js').LGraphNode} LGraphNode*/
/** @type {LGraphNode}*/
export const LGraphNode = LiteGraph.LGraphNode;