Compare commits
28
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f5940ac899 | ||
|
|
67703abb8a | ||
|
|
dfee31f0ed | ||
|
|
894d8e1503 | ||
|
|
08d631d1eb | ||
|
|
a1031487e1 | ||
|
|
ca41207192 | ||
|
|
507d5ef631 | ||
|
|
dd1d9df23f | ||
|
|
3a14e49ca5 | ||
|
|
8147c4bfb7 | ||
|
|
10268825d9 | ||
|
|
f6ea252652 | ||
|
|
98cd5ef79c | ||
|
|
4bce5cadfb | ||
|
|
f362671041 | ||
|
|
0582d1d869 | ||
|
|
ce073a86c7 | ||
|
|
3a85a1edf2 | ||
|
|
369c1456a9 | ||
|
|
01e323b7e2 | ||
|
|
db684d044a | ||
|
|
8e12803ea1 | ||
|
|
7585d5049a | ||
|
|
772bb09240 | ||
|
|
9a7e18e651 | ||
|
|
a02c8d237f | ||
|
|
2ba5a0ff3d |
@@ -8,6 +8,16 @@ class ComfyUIDeployExternalBoolean:
|
||||
{"multiline": False, "default": "input_bool"},
|
||||
),
|
||||
"default_value": ("BOOLEAN", {"default": False})
|
||||
},
|
||||
"optional": {
|
||||
"display_name": (
|
||||
"STRING",
|
||||
{"multiline": False, "default": "Name of the node (optional)"},
|
||||
),
|
||||
"description": (
|
||||
"STRING",
|
||||
{"multiline": True, "default": "Description of the node (optional)"},
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,7 +26,7 @@ class ComfyUIDeployExternalBoolean:
|
||||
|
||||
FUNCTION = "run"
|
||||
|
||||
def run(self, input_id, default_value=None):
|
||||
def run(self, input_id, default_value=None, display_name=None, description=None):
|
||||
print(f"Node '{input_id}' processing with switch set to {default_value}")
|
||||
return [default_value]
|
||||
|
||||
|
||||
@@ -23,6 +23,14 @@ class ComfyUIDeployExternalCheckpoint:
|
||||
},
|
||||
"optional": {
|
||||
"default_value": (folder_paths.get_filename_list("checkpoints"), ),
|
||||
"display_name": (
|
||||
"STRING",
|
||||
{"multiline": False, "default": "Name of the node (optional)"},
|
||||
),
|
||||
"description": (
|
||||
"STRING",
|
||||
{"multiline": True, "default": "Description of the node (optional)"},
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,7 +41,7 @@ class ComfyUIDeployExternalCheckpoint:
|
||||
|
||||
CATEGORY = "deploy"
|
||||
|
||||
def run(self, input_id, default_value=None):
|
||||
def run(self, input_id, default_value=None, display_name=None, description=None):
|
||||
import requests
|
||||
import os
|
||||
import uuid
|
||||
|
||||
@@ -15,6 +15,14 @@ class ComfyUIDeployExternalImage:
|
||||
},
|
||||
"optional": {
|
||||
"default_value": ("IMAGE",),
|
||||
"display_name": (
|
||||
"STRING",
|
||||
{"multiline": False, "default": "Name of the node (optional)"},
|
||||
),
|
||||
"description": (
|
||||
"STRING",
|
||||
{"multiline": True, "default": "Description of the node (optional)"},
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,7 +33,7 @@ class ComfyUIDeployExternalImage:
|
||||
|
||||
CATEGORY = "image"
|
||||
|
||||
def run(self, input_id, default_value=None):
|
||||
def run(self, input_id, default_value=None, display_name=None, description=None):
|
||||
image = default_value
|
||||
try:
|
||||
if input_id.startswith('http'):
|
||||
|
||||
@@ -15,6 +15,14 @@ class ComfyUIDeployExternalImageAlpha:
|
||||
},
|
||||
"optional": {
|
||||
"default_value": ("IMAGE",),
|
||||
"display_name": (
|
||||
"STRING",
|
||||
{"multiline": False, "default": "Name of the node (optional)"},
|
||||
),
|
||||
"description": (
|
||||
"STRING",
|
||||
{"multiline": True, "default": "Description of the node (optional)"},
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,7 +33,7 @@ class ComfyUIDeployExternalImageAlpha:
|
||||
|
||||
CATEGORY = "image"
|
||||
|
||||
def run(self, input_id, default_value=None):
|
||||
def run(self, input_id, default_value=None, display_name=None, description=None):
|
||||
image = default_value
|
||||
try:
|
||||
if input_id.startswith('http'):
|
||||
|
||||
@@ -21,6 +21,14 @@ class ComfyUIDeployExternalImageBatch:
|
||||
},
|
||||
"optional": {
|
||||
"default_value": ("IMAGE",),
|
||||
"display_name": (
|
||||
"STRING",
|
||||
{"multiline": False, "default": "Name of the node (optional)"},
|
||||
),
|
||||
"description": (
|
||||
"STRING",
|
||||
{"multiline": True, "default": "Description of the node (optional)"},
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,7 +39,7 @@ class ComfyUIDeployExternalImageBatch:
|
||||
|
||||
CATEGORY = "image"
|
||||
|
||||
def run(self, input_id, images=None, default_value=None):
|
||||
def run(self, input_id, images=None, default_value=None, display_name=None, description=None):
|
||||
processed_images = []
|
||||
try:
|
||||
images_list = json.loads(images) # Assuming images is a JSON array string
|
||||
|
||||
@@ -4,12 +4,15 @@ import numpy as np
|
||||
import torch
|
||||
import folder_paths
|
||||
|
||||
|
||||
class AnyType(str):
|
||||
def __ne__(self, __value: object) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
WILDCARD = AnyType("*")
|
||||
|
||||
|
||||
class ComfyUIDeployExternalLora:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
@@ -22,6 +25,18 @@ class ComfyUIDeployExternalLora:
|
||||
},
|
||||
"optional": {
|
||||
"default_lora_name": (folder_paths.get_filename_list("loras"),),
|
||||
"lora_save_name": ( # if `default_lora_name` is a link to download a file, we will attempt to save it with this name
|
||||
"STRING",
|
||||
{"multiline": False, "default": ""},
|
||||
),
|
||||
"display_name": (
|
||||
"STRING",
|
||||
{"multiline": False, "default": "Name of the node (optional)"},
|
||||
),
|
||||
"description": (
|
||||
"STRING",
|
||||
{"multiline": True, "default": "Description of the node (optional)"},
|
||||
),
|
||||
},
|
||||
}
|
||||
|
||||
@@ -32,17 +47,24 @@ class ComfyUIDeployExternalLora:
|
||||
|
||||
CATEGORY = "deploy"
|
||||
|
||||
def run(self, input_id, default_lora_name=None):
|
||||
def run(self, input_id, default_lora_name=None, lora_save_name=None, display_name=None, description=None):
|
||||
import requests
|
||||
import os
|
||||
import uuid
|
||||
|
||||
if default_lora_name.startswith("http"):
|
||||
unique_filename = str(uuid.uuid4()) + ".safetensors"
|
||||
print(unique_filename)
|
||||
if lora_save_name:
|
||||
existing_loras = folder_paths.get_filename_list("loras")
|
||||
# Check if lora_save_name exists in the list
|
||||
if lora_save_name in existing_loras:
|
||||
print(f"using lora: {lora_save_name}")
|
||||
return (lora_save_name,)
|
||||
else:
|
||||
lora_save_name = str(uuid.uuid4()) + ".safetensors"
|
||||
print(lora_save_name)
|
||||
print(folder_paths.folder_names_and_paths["loras"][0][0])
|
||||
destination_path = os.path.join(
|
||||
folder_paths.folder_names_and_paths["loras"][0][0], unique_filename
|
||||
folder_paths.folder_names_and_paths["loras"][0][0], lora_save_name
|
||||
)
|
||||
print(destination_path)
|
||||
print("Downloading external lora - " + input_id + " to " + destination_path)
|
||||
@@ -53,7 +75,7 @@ class ComfyUIDeployExternalLora:
|
||||
)
|
||||
with open(destination_path, "wb") as out_file:
|
||||
out_file.write(response.content)
|
||||
return (unique_filename,)
|
||||
return (lora_save_name,)
|
||||
else:
|
||||
print(f"using lora: {default_lora_name}")
|
||||
return (default_lora_name,)
|
||||
|
||||
@@ -16,7 +16,15 @@ class ComfyUIDeployExternalNumber:
|
||||
"optional": {
|
||||
"default_value": (
|
||||
"FLOAT",
|
||||
{"multiline": True, "display": "number", "default": 0, "step": 0.01},
|
||||
{"multiline": True, "display": "number", "default": 0, "min": -2147483647, "max": 2147483647, "step": 0.01},
|
||||
),
|
||||
"display_name": (
|
||||
"STRING",
|
||||
{"multiline": False, "default": "Name of the node (optional)"},
|
||||
),
|
||||
"description": (
|
||||
"STRING",
|
||||
{"multiline": True, "default": "Description of the node (optional)"},
|
||||
),
|
||||
}
|
||||
}
|
||||
@@ -28,7 +36,7 @@ class ComfyUIDeployExternalNumber:
|
||||
|
||||
CATEGORY = "number"
|
||||
|
||||
def run(self, input_id, default_value=None):
|
||||
def run(self, input_id, default_value=None, display_name=None, description=None):
|
||||
try:
|
||||
float_value = float(input_id)
|
||||
print("my number", float_value)
|
||||
|
||||
@@ -16,7 +16,15 @@ class ComfyUIDeployExternalNumberInt:
|
||||
"optional": {
|
||||
"default_value": (
|
||||
"INT",
|
||||
{"multiline": True, "display": "number", "default": 0},
|
||||
{"multiline": True, "display": "number", "min": -2147483647, "max": 2147483647, "default": 0},
|
||||
),
|
||||
"display_name": (
|
||||
"STRING",
|
||||
{"multiline": False, "default": "Name of the node (optional)"},
|
||||
),
|
||||
"description": (
|
||||
"STRING",
|
||||
{"multiline": True, "default": "Description of the node (optional)"},
|
||||
),
|
||||
}
|
||||
}
|
||||
@@ -28,7 +36,7 @@ class ComfyUIDeployExternalNumberInt:
|
||||
|
||||
CATEGORY = "number"
|
||||
|
||||
def run(self, input_id, default_value=None):
|
||||
def run(self, input_id, default_value=None, display_name=None, description=None):
|
||||
if not input_id or (isinstance(input_id, str) and not input_id.strip().isdigit()):
|
||||
return [default_value]
|
||||
return [int(input_id)]
|
||||
|
||||
@@ -11,15 +11,23 @@ class ComfyUIDeployExternalNumberSlider:
|
||||
"optional": {
|
||||
"default_value": (
|
||||
"FLOAT",
|
||||
{"multiline": True, "display": "number", "default": 0.5, "step": 0.01},
|
||||
{"multiline": True, "display": "number", "min": -2147483647, "max": 2147483647, "default": 0.5, "step": 0.01},
|
||||
),
|
||||
"min_value": (
|
||||
"FLOAT",
|
||||
{"multiline": True, "display": "number", "default": 0, "step": 0.01},
|
||||
{"multiline": True, "display": "number", "min": -2147483647, "max": 2147483647, "default": 0, "step": 0.01},
|
||||
),
|
||||
"max_value": (
|
||||
"FLOAT",
|
||||
{"multiline": True, "display": "number", "default": 1, "step": 0.01},
|
||||
{"multiline": True, "display": "number", "min": -2147483647, "max": 2147483647, "default": 1, "step": 0.01},
|
||||
),
|
||||
"display_name": (
|
||||
"STRING",
|
||||
{"multiline": False, "default": "Name of the node (optional)"},
|
||||
),
|
||||
"description": (
|
||||
"STRING",
|
||||
{"multiline": True, "default": "Description of the node (optional)"},
|
||||
),
|
||||
}
|
||||
}
|
||||
@@ -31,7 +39,7 @@ class ComfyUIDeployExternalNumberSlider:
|
||||
|
||||
CATEGORY = "number"
|
||||
|
||||
def run(self, input_id, default_value=None, min_value=0, max_value=1):
|
||||
def run(self, input_id, default_value=None, min_value=0, max_value=1, display_name=None, description=None):
|
||||
try:
|
||||
float_value = float(input_id)
|
||||
if min_value <= float_value <= max_value:
|
||||
|
||||
@@ -18,6 +18,14 @@ class ComfyUIDeployExternalText:
|
||||
"STRING",
|
||||
{"multiline": True, "default": ""},
|
||||
),
|
||||
"display_name": (
|
||||
"STRING",
|
||||
{"multiline": False, "default": "Name of the node (optional)"},
|
||||
),
|
||||
"description": (
|
||||
"STRING",
|
||||
{"multiline": True, "default": "Description of the node (optional)"},
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,7 +36,7 @@ class ComfyUIDeployExternalText:
|
||||
|
||||
CATEGORY = "text"
|
||||
|
||||
def run(self, input_id, default_value=None):
|
||||
def run(self, input_id, default_value=None, display_name=None, description=None):
|
||||
return [default_value]
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import folder_paths
|
||||
from PIL import Image, ImageOps
|
||||
import numpy as np
|
||||
import torch
|
||||
import json
|
||||
|
||||
class ComfyUIDeployExternalTextList:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": {
|
||||
"input_id": (
|
||||
"STRING",
|
||||
{"multiline": False, "default": 'input_text_list'},
|
||||
),
|
||||
"text": (
|
||||
"STRING",
|
||||
{"multiline": True, "default": "[]"},
|
||||
),
|
||||
},
|
||||
"optional": {
|
||||
"display_name": (
|
||||
"STRING",
|
||||
{"multiline": False, "default": "Name of the node (optional)"},
|
||||
),
|
||||
"description": (
|
||||
"STRING",
|
||||
{"multiline": True, "default": "Description of the node (optional)"},
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("STRING",)
|
||||
RETURN_NAMES = ("text",)
|
||||
|
||||
OUTPUT_IS_LIST = (True,)
|
||||
|
||||
FUNCTION = "run"
|
||||
|
||||
CATEGORY = "text"
|
||||
|
||||
def run(self, input_id, text=None, display_name=None, description=None):
|
||||
text_list = []
|
||||
try:
|
||||
text_list = json.loads(text) # Assuming text is a JSON array string
|
||||
except Exception as e:
|
||||
print(f"Error processing images: {e}")
|
||||
pass
|
||||
return ([text_list],)
|
||||
|
||||
NODE_CLASS_MAPPINGS = {"ComfyUIDeployExternalTextList": ComfyUIDeployExternalTextList}
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {"ComfyUIDeployExternalTextList": "External Text List (ComfyUI Deploy)"}
|
||||
@@ -765,6 +765,14 @@ class ComfyUIDeployExternalVideo:
|
||||
"meta_batch": ("VHS_BatchManager",),
|
||||
"vae": ("VAE",),
|
||||
"default_value": (sorted(files),),
|
||||
"display_name": (
|
||||
"STRING",
|
||||
{"multiline": False, "default": "Name of the node (optional)"},
|
||||
),
|
||||
"description": (
|
||||
"STRING",
|
||||
{"multiline": True, "default": "Description of the node (optional)"},
|
||||
),
|
||||
},
|
||||
"hidden": {
|
||||
"unique_id": "UNIQUE_ID"
|
||||
@@ -796,8 +804,6 @@ class ComfyUIDeployExternalVideo:
|
||||
meta_batch = kwargs.get("meta_batch")
|
||||
unique_id = kwargs.get("unique_id")
|
||||
|
||||
video = kwargs.get("default_value")
|
||||
video_path = folder_paths.get_annotated_filepath(video.strip('"'))
|
||||
|
||||
input_dir = folder_paths.get_input_directory()
|
||||
if input_id.startswith("http"):
|
||||
@@ -827,8 +833,11 @@ class ComfyUIDeployExternalVideo:
|
||||
leave=True,
|
||||
):
|
||||
out_file.write(chunk)
|
||||
|
||||
print("video path: ", video_path)
|
||||
else:
|
||||
video = kwargs.get("default_value", "")
|
||||
if video is None:
|
||||
raise "No default video given and no external video provided"
|
||||
video_path = folder_paths.get_annotated_filepath(video.strip('"'))
|
||||
|
||||
return load_video_cv(
|
||||
video=video_path,
|
||||
|
||||
+112
-25
@@ -17,12 +17,13 @@ from urllib.parse import quote
|
||||
import threading
|
||||
import hashlib
|
||||
import aiohttp
|
||||
from aiohttp import ClientSession, web
|
||||
import aiofiles
|
||||
from typing import Dict, List, Union, Any, Optional
|
||||
from PIL import Image
|
||||
import copy
|
||||
import struct
|
||||
from aiohttp import ClientError
|
||||
from aiohttp import web, ClientSession, ClientError, ClientTimeout
|
||||
import atexit
|
||||
|
||||
# Global session
|
||||
@@ -50,29 +51,45 @@ def exit_handler():
|
||||
|
||||
atexit.register(exit_handler)
|
||||
|
||||
max_retries = int(os.environ.get('MAX_RETRIES', '3'))
|
||||
max_retries = int(os.environ.get('MAX_RETRIES', '5'))
|
||||
retry_delay_multiplier = float(os.environ.get('RETRY_DELAY_MULTIPLIER', '2'))
|
||||
|
||||
print(f"max_retries: {max_retries}, retry_delay_multiplier: {retry_delay_multiplier}")
|
||||
|
||||
async def async_request_with_retry(method, url, **kwargs):
|
||||
async def async_request_with_retry(method, url, disable_timeout=False, **kwargs):
|
||||
global client_session
|
||||
await ensure_client_session()
|
||||
# async with aiohttp.ClientSession() as client_session:
|
||||
retry_delay = 1 # Start with 1 second delay
|
||||
initial_timeout = 5 # 5 seconds timeout for the initial connection
|
||||
|
||||
for attempt in range(max_retries):
|
||||
try:
|
||||
# Set a timeout for the initial connection
|
||||
if not disable_timeout:
|
||||
timeout = ClientTimeout(total=None, connect=initial_timeout)
|
||||
kwargs['timeout'] = timeout
|
||||
|
||||
async with client_session.request(method, url, **kwargs) as response:
|
||||
response.raise_for_status()
|
||||
if method.upper() == 'GET':
|
||||
await response.read()
|
||||
return response
|
||||
except asyncio.TimeoutError:
|
||||
logger.warning(f"Request timed out after {initial_timeout} seconds (attempt {attempt + 1}/{max_retries})")
|
||||
except ClientError as e:
|
||||
if attempt == max_retries - 1:
|
||||
logger.error(f"Request failed after {max_retries} attempts: {e}")
|
||||
# raise
|
||||
logger.warning(f"Request failed (attempt {attempt + 1}/{max_retries}): {e}")
|
||||
|
||||
# Wait before retrying
|
||||
await asyncio.sleep(retry_delay)
|
||||
retry_delay *= retry_delay_multiplier # Exponential backoff
|
||||
|
||||
# If all retries fail, raise an exception
|
||||
raise Exception(f"Request failed after {max_retries} attempts")
|
||||
|
||||
from logging import basicConfig, getLogger
|
||||
|
||||
# Check for an environment variable to enable/disable Logfire
|
||||
@@ -108,7 +125,8 @@ def log_span(name):
|
||||
if use_logfire:
|
||||
with logger.span(name):
|
||||
yield
|
||||
# else:
|
||||
else:
|
||||
yield
|
||||
# logger.info(f"Start: {name}")
|
||||
# yield
|
||||
# logger.info(f"End: {name}")
|
||||
@@ -216,15 +234,32 @@ def apply_random_seed_to_workflow(workflow_api):
|
||||
workflow_api (dict): The workflow API dictionary to modify.
|
||||
"""
|
||||
for key in workflow_api:
|
||||
if 'inputs' in workflow_api[key] and 'seed' in workflow_api[key]['inputs']:
|
||||
if 'inputs' in workflow_api[key]:
|
||||
if 'seed' in workflow_api[key]['inputs']:
|
||||
if isinstance(workflow_api[key]['inputs']['seed'], list):
|
||||
continue
|
||||
if workflow_api[key]['class_type'] == "PromptExpansion":
|
||||
workflow_api[key]['inputs']['seed'] = randomSeed(8);
|
||||
workflow_api[key]['inputs']['seed'] = randomSeed(8)
|
||||
logger.info(f"Applied random seed {workflow_api[key]['inputs']['seed']} to PromptExpansion")
|
||||
continue
|
||||
workflow_api[key]['inputs']['seed'] = randomSeed();
|
||||
workflow_api[key]['inputs']['seed'] = randomSeed()
|
||||
logger.info(f"Applied random seed {workflow_api[key]['inputs']['seed']} to {workflow_api[key]['class_type']}")
|
||||
|
||||
def apply_inputs_to_workflow(workflow_api: Any, inputs: Any, sid: str = None):
|
||||
if 'noise_seed' in workflow_api[key]['inputs']:
|
||||
if workflow_api[key]['class_type'] == "RandomNoise":
|
||||
workflow_api[key]['inputs']['noise_seed'] = randomSeed()
|
||||
logger.info(f"Applied random noise_seed {workflow_api[key]['inputs']['noise_seed']} to RandomNoise")
|
||||
continue
|
||||
if workflow_api[key]['class_type'] == "KSamplerAdvanced":
|
||||
workflow_api[key]['inputs']['noise_seed'] = randomSeed()
|
||||
logger.info(f"Applied random noise_seed {workflow_api[key]['inputs']['noise_seed']} to KSamplerAdvanced")
|
||||
continue
|
||||
if workflow_api[key]['class_type'] == "SamplerCustom":
|
||||
workflow_api[key]['inputs']['noise_seed'] = randomSeed()
|
||||
logger.info(f"Applied random noise_seed {workflow_api[key]['inputs']['noise_seed']} to SamplerCustom")
|
||||
continue
|
||||
|
||||
def apply_inputs_to_workflow(workflow_api: Any, inputs: Any, sid: str | None = None):
|
||||
# Loop through each of the inputs and replace them
|
||||
for key, value in workflow_api.items():
|
||||
if 'inputs' in value:
|
||||
@@ -348,7 +383,7 @@ async def comfy_deploy_run(request):
|
||||
|
||||
status = 200
|
||||
|
||||
if "node_errors" in res and res["node_errors"]:
|
||||
if "node_errors" in res and res["node_errors"] is not None and len(res["node_errors"]) > 0:
|
||||
# Even tho there are node_errors it can still be run
|
||||
status = 400
|
||||
await update_run_with_output(prompt_id, {
|
||||
@@ -386,7 +421,7 @@ async def stream_prompt(data):
|
||||
workflow_api=workflow_api
|
||||
)
|
||||
|
||||
log('info', "Begin prompt", prompt=prompt)
|
||||
# log('info', "Begin prompt", prompt=prompt)
|
||||
|
||||
try:
|
||||
res = post_prompt(prompt)
|
||||
@@ -409,7 +444,7 @@ async def stream_prompt(data):
|
||||
|
||||
status = 200
|
||||
|
||||
if "node_errors" in res and res["node_errors"]:
|
||||
if "node_errors" in res and res["node_errors"] is not None and len(res["node_errors"]) > 0:
|
||||
# Even tho there are node_errors it can still be run
|
||||
status = 400
|
||||
await update_run_with_output(prompt_id, {
|
||||
@@ -453,7 +488,7 @@ async def stream_response(request):
|
||||
if not comfy_message_queues[prompt_id].empty():
|
||||
data = await comfy_message_queues[prompt_id].get()
|
||||
|
||||
log('info', data["event"], data=json.dumps(data))
|
||||
# log('info', data["event"], data=json.dumps(data))
|
||||
# logger.info("listener", data)
|
||||
await response.write(f"event: event_update\ndata: {json.dumps(data)}\n\n".encode('utf-8'))
|
||||
await response.drain() # Ensure the buffer is flushed
|
||||
@@ -821,6 +856,50 @@ async def send(event, data, sid=None):
|
||||
logger.info(f"Exception: {e}")
|
||||
traceback.print_exc()
|
||||
|
||||
@server.PromptServer.instance.routes.get('/comfydeploy/{tail:.*}')
|
||||
@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"]}'
|
||||
|
||||
# Get all query parameters
|
||||
query_params = request.query_string
|
||||
|
||||
# Construct the full target URL with query parameters
|
||||
target_url = f"{base_url}?{query_params}" if query_params else base_url
|
||||
|
||||
# print(f"Proxying request to: {target_url}")
|
||||
|
||||
try:
|
||||
# Create a new ClientSession for each request
|
||||
async with ClientSession() as client_session:
|
||||
# Forward the request
|
||||
client_req = await client_session.request(
|
||||
method=request.method,
|
||||
url=target_url,
|
||||
headers={k: v for k, v in request.headers.items() if k.lower() not in ('host', 'content-length')},
|
||||
data=await request.read(),
|
||||
allow_redirects=False,
|
||||
)
|
||||
|
||||
# Read the entire response content
|
||||
content = await client_req.read()
|
||||
|
||||
# Try to decode the content as JSON
|
||||
try:
|
||||
json_data = json.loads(content)
|
||||
# If successful, return a JSON response
|
||||
return web.json_response(json_data, status=client_req.status)
|
||||
except json.JSONDecodeError:
|
||||
# If it's not valid JSON, return the content as-is
|
||||
return web.Response(body=content, status=client_req.status, headers=client_req.headers)
|
||||
|
||||
except ClientError as e:
|
||||
print(f"Client error occurred while proxying request: {str(e)}")
|
||||
return web.Response(status=502, text=f"Bad Gateway: {str(e)}")
|
||||
except Exception as e:
|
||||
print(f"Error occurred while proxying request: {str(e)}")
|
||||
return web.Response(status=500, text=f"Internal Server Error: {str(e)}")
|
||||
|
||||
|
||||
prompt_server = server.PromptServer.instance
|
||||
@@ -1078,18 +1157,18 @@ async def upload_file(prompt_id, filename, subfolder=None, content_type="image/p
|
||||
prompt_id = quote(prompt_id)
|
||||
content_type = quote(content_type)
|
||||
|
||||
target_url = f"{file_upload_endpoint}?file_name={filename}&run_id={prompt_id}&type={content_type}"
|
||||
target_url = f"{file_upload_endpoint}?file_name={filename}&run_id={prompt_id}&type={content_type}&version=v2"
|
||||
|
||||
start_time = time.time() # Start timing here
|
||||
result = requests.get(target_url)
|
||||
result = await async_request_with_retry("GET", target_url, disable_timeout=True)
|
||||
end_time = time.time() # End timing after the request is complete
|
||||
logger.info("Time taken for getting file upload endpoint: {:.2f} seconds".format(end_time - start_time))
|
||||
ok = result.json()
|
||||
ok = await result.json()
|
||||
|
||||
start_time = time.time() # Start timing here
|
||||
|
||||
with open(file, 'rb') as f:
|
||||
data = f.read()
|
||||
async with aiofiles.open(file, 'rb') as f:
|
||||
data = await f.read()
|
||||
headers = {
|
||||
# "x-amz-acl": "public-read",
|
||||
"Content-Type": content_type,
|
||||
@@ -1192,8 +1271,10 @@ async def update_file_status(prompt_id: str, data, uploading, have_error=False,
|
||||
|
||||
async def handle_upload(prompt_id: str, data, key: str, content_type_key: str, default_content_type: str):
|
||||
items = data.get(key, [])
|
||||
upload_tasks = []
|
||||
|
||||
for item in items:
|
||||
# # Skipping temp files
|
||||
# Skipping temp files
|
||||
if item.get("type") == "temp":
|
||||
continue
|
||||
|
||||
@@ -1206,22 +1287,28 @@ async def handle_upload(prompt_id: str, data, key: str, content_type_key: str, d
|
||||
elif file_extension == '.webp':
|
||||
file_type = 'image/webp'
|
||||
|
||||
await upload_file(
|
||||
upload_tasks.append(upload_file(
|
||||
prompt_id,
|
||||
item.get("filename"),
|
||||
subfolder=item.get("subfolder"),
|
||||
type=item.get("type"),
|
||||
content_type=file_type
|
||||
)
|
||||
))
|
||||
|
||||
# Execute all upload tasks concurrently
|
||||
await asyncio.gather(*upload_tasks)
|
||||
|
||||
# Upload files in the background
|
||||
async def upload_in_background(prompt_id: str, data, node_id=None, have_upload=True):
|
||||
try:
|
||||
await handle_upload(prompt_id, data, 'images', "content_type", "image/png")
|
||||
await handle_upload(prompt_id, data, 'files', "content_type", "image/png")
|
||||
# This will also be mp4
|
||||
await handle_upload(prompt_id, data, 'gifs', "format", "image/gif")
|
||||
await handle_upload(prompt_id, data, 'mesh', "format", "application/octet-stream")
|
||||
upload_tasks = [
|
||||
handle_upload(prompt_id, data, 'images', "content_type", "image/png"),
|
||||
handle_upload(prompt_id, data, 'files', "content_type", "image/png"),
|
||||
handle_upload(prompt_id, data, 'gifs', "format", "image/gif"),
|
||||
handle_upload(prompt_id, data, 'mesh', "format", "application/octet-stream")
|
||||
]
|
||||
|
||||
await asyncio.gather(*upload_tasks)
|
||||
|
||||
if have_upload:
|
||||
await update_file_status(prompt_id, data, False, node_id=node_id)
|
||||
|
||||
@@ -2,4 +2,5 @@ aiofiles
|
||||
pydantic
|
||||
opencv-python
|
||||
imageio-ffmpeg
|
||||
brotli
|
||||
# logfire
|
||||
+327
-37
@@ -2,6 +2,7 @@ import { app } from "./app.js";
|
||||
import { api } from "./api.js";
|
||||
import { ComfyWidgets, LGraphNode } from "./widgets.js";
|
||||
import { generateDependencyGraph } from "https://esm.sh/[email protected]";
|
||||
import { ComfyDeploy } from "https://esm.sh/[email protected]";
|
||||
|
||||
const loadingIcon = `<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24"><g fill="none" stroke="#888888" stroke-linecap="round" stroke-width="2"><path stroke-dasharray="60" stroke-dashoffset="60" stroke-opacity=".3" d="M12 3C16.9706 3 21 7.02944 21 12C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12C3 7.02944 7.02944 3 12 3Z"><animate fill="freeze" attributeName="stroke-dashoffset" dur="1.3s" values="60;0"/></path><path stroke-dasharray="15" stroke-dashoffset="15" d="M12 3C16.9706 3 21 7.02944 21 12"><animate fill="freeze" attributeName="stroke-dashoffset" dur="0.3s" values="15;0"/><animateTransform attributeName="transform" dur="1.5s" repeatCount="indefinite" type="rotate" values="0 12 12;360 12 12"/></path></g></svg>`;
|
||||
|
||||
@@ -206,14 +207,26 @@ const ext = {
|
||||
ComfyWidgets.STRING(
|
||||
this,
|
||||
"workflow_name",
|
||||
["", { default: this.properties.workflow_name, multiline: false }],
|
||||
[
|
||||
"",
|
||||
{
|
||||
default: this.properties.workflow_name,
|
||||
multiline: false,
|
||||
},
|
||||
],
|
||||
app,
|
||||
);
|
||||
|
||||
ComfyWidgets.STRING(
|
||||
this,
|
||||
"workflow_id",
|
||||
["", { default: this.properties.workflow_id, multiline: false }],
|
||||
[
|
||||
"",
|
||||
{
|
||||
default: this.properties.workflow_id,
|
||||
multiline: false,
|
||||
},
|
||||
],
|
||||
app,
|
||||
);
|
||||
|
||||
@@ -278,7 +291,11 @@ const ext = {
|
||||
sendEventToCD("cd_plugin_onDeployChanges", prompt);
|
||||
} else if (message.type === "queue_prompt") {
|
||||
const prompt = await app.graphToPrompt();
|
||||
if (typeof api.handlePromptGenerated === "function") {
|
||||
api.handlePromptGenerated(prompt);
|
||||
} else {
|
||||
console.warn("api.handlePromptGenerated is not a function");
|
||||
}
|
||||
sendEventToCD("cd_plugin_onQueuePrompt", prompt);
|
||||
} else if (message.type === "get_prompt") {
|
||||
const prompt = await app.graphToPrompt();
|
||||
@@ -301,6 +318,56 @@ const ext = {
|
||||
|
||||
app.graph.add(node);
|
||||
app.graph.afterChange();
|
||||
} else if (message.type === "zoom_to_node") {
|
||||
const nodeId = message.data.nodeId;
|
||||
const position = message.data.position;
|
||||
|
||||
const node = app.graph.getNodeById(nodeId);
|
||||
if (!node) return;
|
||||
|
||||
const canvas = app.canvas;
|
||||
const targetScale = 1;
|
||||
const targetOffsetX =
|
||||
canvas.canvas.width / 4 - position[0] - node.size[0] / 2;
|
||||
const targetOffsetY =
|
||||
canvas.canvas.height / 4 - position[1] - node.size[1] / 2;
|
||||
|
||||
const startScale = canvas.ds.scale;
|
||||
const startOffsetX = canvas.ds.offset[0];
|
||||
const startOffsetY = canvas.ds.offset[1];
|
||||
|
||||
const duration = 400; // Animation duration in milliseconds
|
||||
const startTime = Date.now();
|
||||
|
||||
function easeOutCubic(t) {
|
||||
return 1 - Math.pow(1 - t, 3);
|
||||
}
|
||||
|
||||
function lerp(start, end, t) {
|
||||
return start * (1 - t) + end * t;
|
||||
}
|
||||
|
||||
function animate() {
|
||||
const currentTime = Date.now();
|
||||
const elapsedTime = currentTime - startTime;
|
||||
const t = Math.min(elapsedTime / duration, 1);
|
||||
|
||||
const easedT = easeOutCubic(t);
|
||||
|
||||
const currentScale = lerp(startScale, targetScale, easedT);
|
||||
const currentOffsetX = lerp(startOffsetX, targetOffsetX, easedT);
|
||||
const currentOffsetY = lerp(startOffsetY, targetOffsetY, easedT);
|
||||
|
||||
canvas.setZoom(currentScale);
|
||||
canvas.ds.offset = [currentOffsetX, currentOffsetY];
|
||||
canvas.draw(true, true);
|
||||
|
||||
if (t < 1) {
|
||||
requestAnimationFrame(animate);
|
||||
}
|
||||
}
|
||||
|
||||
animate();
|
||||
}
|
||||
// else if (message.type === "refresh") {
|
||||
// sendEventToCD("cd_plugin_onRefresh");
|
||||
@@ -375,11 +442,14 @@ function createDynamicUIHtml(data) {
|
||||
Object.values(data.custom_nodes).forEach((node) => {
|
||||
html += `
|
||||
<div style="border-bottom: 1px solid #e2e8f0; padding-top: 16px;">
|
||||
<a href="${node.url
|
||||
}" target="_blank" style="font-size: 18px; font-weight: semibold; color: white; text-decoration: none;">${node.name
|
||||
<a href="${
|
||||
node.url
|
||||
}" target="_blank" style="font-size: 18px; font-weight: semibold; color: white; text-decoration: none;">${
|
||||
node.name
|
||||
}</a>
|
||||
<p style="font-size: 14px; color: #4b5563;">${node.hash}</p>
|
||||
${node.warning
|
||||
${
|
||||
node.warning
|
||||
? `<p style="font-size: 14px; color: #d69e2e;">${node.warning}</p>`
|
||||
: ""
|
||||
}
|
||||
@@ -396,7 +466,8 @@ function createDynamicUIHtml(data) {
|
||||
Object.entries(data.models).forEach(([section, items]) => {
|
||||
html += `
|
||||
<div style="border-bottom: 1px solid #e2e8f0; padding-top: 8px; padding-bottom: 8px;">
|
||||
<h3 style="font-size: 18px; font-weight: semibold; margin-bottom: 8px;">${section.charAt(0).toUpperCase() + section.slice(1)
|
||||
<h3 style="font-size: 18px; font-weight: semibold; margin-bottom: 8px;">${
|
||||
section.charAt(0).toUpperCase() + section.slice(1)
|
||||
}</h3>`;
|
||||
items.forEach((item) => {
|
||||
html += `<p style="font-size: 14px; color: ${textColor};">${item.name}</p>`;
|
||||
@@ -413,7 +484,8 @@ function createDynamicUIHtml(data) {
|
||||
Object.entries(data.files).forEach(([section, items]) => {
|
||||
html += `
|
||||
<div style="border-bottom: 1px solid #e2e8f0; padding-top: 8px; padding-bottom: 8px;">
|
||||
<h3 style="font-size: 18px; font-weight: semibold; margin-bottom: 8px;">${section.charAt(0).toUpperCase() + section.slice(1)
|
||||
<h3 style="font-size: 18px; font-weight: semibold; margin-bottom: 8px;">${
|
||||
section.charAt(0).toUpperCase() + section.slice(1)
|
||||
}</h3>`;
|
||||
items.forEach((item) => {
|
||||
html += `<p style="font-size: 14px; color: ${textColor};">${item.name}</p>`;
|
||||
@@ -426,6 +498,7 @@ function createDynamicUIHtml(data) {
|
||||
return html;
|
||||
}
|
||||
|
||||
// Modify the existing deployWorkflow function
|
||||
async function deployWorkflow() {
|
||||
const deploy = document.getElementById("deploy-button");
|
||||
|
||||
@@ -572,30 +645,30 @@ async function deployWorkflow() {
|
||||
console.log(hash);
|
||||
return hash.file_hash;
|
||||
},
|
||||
handleFileUpload: async (file, hash, prevhash) => {
|
||||
console.log("Uploading ", file);
|
||||
loadingDialog.showLoading("Uploading file", file);
|
||||
try {
|
||||
const { download_url } = await fetch(`/comfyui-deploy/upload-file`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
file_path: file,
|
||||
token: apiKey,
|
||||
url: endpoint + "/api/upload-url",
|
||||
}),
|
||||
})
|
||||
.then((x) => x.json())
|
||||
.catch(() => {
|
||||
loadingDialog.close();
|
||||
confirmDialog.confirm("Error", "Unable to upload file " + file);
|
||||
});
|
||||
loadingDialog.showLoading("Uploaded file", file);
|
||||
console.log(download_url);
|
||||
return download_url;
|
||||
} catch (error) {
|
||||
return undefined;
|
||||
}
|
||||
},
|
||||
// handleFileUpload: async (file, hash, prevhash) => {
|
||||
// console.log("Uploading ", file);
|
||||
// loadingDialog.showLoading("Uploading file", file);
|
||||
// try {
|
||||
// const { download_url } = await fetch(`/comfyui-deploy/upload-file`, {
|
||||
// method: "POST",
|
||||
// body: JSON.stringify({
|
||||
// file_path: file,
|
||||
// token: apiKey,
|
||||
// url: endpoint + "/api/upload-url",
|
||||
// }),
|
||||
// })
|
||||
// .then((x) => x.json())
|
||||
// .catch(() => {
|
||||
// loadingDialog.close();
|
||||
// confirmDialog.confirm("Error", "Unable to upload file " + file);
|
||||
// });
|
||||
// loadingDialog.showLoading("Uploaded file", file);
|
||||
// console.log(download_url);
|
||||
// return download_url;
|
||||
// } catch (error) {
|
||||
// return undefined;
|
||||
// }
|
||||
// },
|
||||
existingDependencies: existing_workflow.dependencies,
|
||||
});
|
||||
|
||||
@@ -620,6 +693,15 @@ async function deployWorkflow() {
|
||||
"Check dependencies",
|
||||
// JSON.stringify(deps, null, 2),
|
||||
`
|
||||
<div>
|
||||
You will need to create a cloud machine with the following configuration on ComfyDeploy
|
||||
<ol style="text-align: left; margin-top: 10px;">
|
||||
<li>Review the dependencies listed in the graph below</li>
|
||||
<li>Create a new cloud machine with the required configuration</li>
|
||||
<li>Install missing models and check missing files</li>
|
||||
<li>Deploy your workflow to the newly created machine</li>
|
||||
</ol>
|
||||
</div>
|
||||
<div style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);">${loadingIcon}</div>
|
||||
<iframe
|
||||
style="z-index: 10; min-width: 600px; max-width: 1024px; min-height: 600px; border: none; background-color: transparent;"
|
||||
@@ -689,6 +771,14 @@ async function deployWorkflow() {
|
||||
`<span style="color:green;">Deployed successfully!</span> <a style="color:white;" target="_blank" href=${endpoint}/workflows/${data.workflow_id}>-> View here</a> <br/> <br/> Workflow ID: ${data.workflow_id} <br/> Workflow Name: ${workflow_name} <br/> Workflow Version: ${data.version} <br/>`,
|
||||
);
|
||||
|
||||
// // Refresh the workflows list in the sidebar
|
||||
// const sidebarEl = document.querySelector(
|
||||
// '.comfy-sidebar-tab[data-id="search"]',
|
||||
// );
|
||||
// if (sidebarEl) {
|
||||
// refreshWorkflowsList(sidebarEl);
|
||||
// }
|
||||
|
||||
setTimeout(() => {
|
||||
title.textContent = "Deploy";
|
||||
title.style.color = "white";
|
||||
@@ -706,6 +796,85 @@ async function deployWorkflow() {
|
||||
}
|
||||
}
|
||||
|
||||
// Add this function to refresh the workflows list
|
||||
function refreshWorkflowsList(el) {
|
||||
const workflowsList = el.querySelector("#workflows-list");
|
||||
const workflowsLoading = el.querySelector("#workflows-loading");
|
||||
|
||||
workflowsLoading.style.display = "flex";
|
||||
workflowsList.style.display = "none";
|
||||
workflowsList.innerHTML = "";
|
||||
|
||||
client.workflows
|
||||
.getAll({
|
||||
page: "1",
|
||||
pageSize: "10",
|
||||
})
|
||||
.then((result) => {
|
||||
workflowsLoading.style.display = "none";
|
||||
workflowsList.style.display = "block";
|
||||
|
||||
if (result.length === 0) {
|
||||
workflowsList.innerHTML =
|
||||
"<li style='color: #bdbdbd;'>No workflows found</li>";
|
||||
return;
|
||||
}
|
||||
|
||||
result.forEach((workflow) => {
|
||||
const li = document.createElement("li");
|
||||
li.style.marginBottom = "15px";
|
||||
li.style.padding = "15px";
|
||||
li.style.backgroundColor = "#2a2a2a";
|
||||
li.style.borderRadius = "8px";
|
||||
li.style.boxShadow = "0 2px 4px rgba(0,0,0,0.1)";
|
||||
|
||||
const lastRun = workflow.runs[0];
|
||||
const lastRunStatus = lastRun ? lastRun.status : "No runs";
|
||||
const statusColor =
|
||||
lastRunStatus === "success"
|
||||
? "#4CAF50"
|
||||
: lastRunStatus === "error"
|
||||
? "#F44336"
|
||||
: "#FFC107";
|
||||
|
||||
const timeAgo = getTimeAgo(new Date(workflow.updatedAt));
|
||||
|
||||
li.innerHTML = `
|
||||
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
|
||||
<div style="flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
|
||||
<strong style="font-size: 18px; color: #e0e0e0;">${workflow.name}</strong>
|
||||
</div>
|
||||
<span style="font-size: 12px; color: ${statusColor}; margin-left: 10px;">Last run: ${lastRunStatus}</span>
|
||||
</div>
|
||||
<div style="font-size: 14px; color: #bdbdbd; margin-bottom: 10px;">Last updated ${timeAgo}</div>
|
||||
<div style="display: flex; gap: 10px;">
|
||||
<button class="open-cloud-btn" style="padding: 5px 10px; background-color: #4CAF50; color: white; border: none; border-radius: 4px; cursor: pointer;">Open in Cloud</button>
|
||||
<button class="load-api-btn" style="padding: 5px 10px; background-color: #2196F3; color: white; border: none; border-radius: 4px; cursor: pointer;">Load Workflow</button>
|
||||
</div>
|
||||
`;
|
||||
|
||||
const openCloudBtn = li.querySelector(".open-cloud-btn");
|
||||
openCloudBtn.onclick = () =>
|
||||
window.open(
|
||||
`${getData().endpoint}/workflows/${workflow.id}?workspace=true`,
|
||||
"_blank",
|
||||
);
|
||||
|
||||
const loadApiBtn = li.querySelector(".load-api-btn");
|
||||
loadApiBtn.onclick = () => loadWorkflowApi(workflow.versions[0].id);
|
||||
|
||||
workflowsList.appendChild(li);
|
||||
});
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error("Error fetching workflows:", error);
|
||||
workflowsLoading.style.display = "none";
|
||||
workflowsList.style.display = "block";
|
||||
workflowsList.innerHTML =
|
||||
"<li style='color: #F44336;'>Error fetching workflows</li>";
|
||||
});
|
||||
}
|
||||
|
||||
function addButton() {
|
||||
const menu = document.querySelector(".comfy-menu");
|
||||
|
||||
@@ -837,9 +1006,11 @@ export class LoadingDialog extends ComfyDialog {
|
||||
showLoading(title, message) {
|
||||
this.show(`
|
||||
<div style="width: 400px; display: flex; gap: 18px; flex-direction: column; overflow: unset">
|
||||
<h3 style="margin: 0px; display: flex; align-items: center; justify-content: center; gap: 12px;">${title} ${this.loadingIcon
|
||||
<h3 style="margin: 0px; display: flex; align-items: center; justify-content: center; gap: 12px;">${title} ${
|
||||
this.loadingIcon
|
||||
}</h3>
|
||||
${message
|
||||
${
|
||||
message
|
||||
? `<label style="max-width: 100%; white-space: pre-wrap; word-wrap: break-word;">${message}</label>`
|
||||
: ""
|
||||
}
|
||||
@@ -1108,16 +1279,20 @@ export class ConfigDialog extends ComfyDialog {
|
||||
</label>
|
||||
<label style="color: white; width: 100%;">
|
||||
Endpoint:
|
||||
<input id="endpoint" style="margin-top: 8px; width: 100%; height:40px; box-sizing: border-box; padding: 0px 6px;" type="text" value="${data.endpoint
|
||||
<input id="endpoint" style="margin-top: 8px; width: 100%; height:40px; box-sizing: border-box; padding: 0px 6px;" type="text" value="${
|
||||
data.endpoint
|
||||
}">
|
||||
</label>
|
||||
<div style="color: white;">
|
||||
API Key: User / Org <button style="font-size: 18px;">${data.displayName ?? ""
|
||||
API Key: User / Org <button style="font-size: 18px;">${
|
||||
data.displayName ?? ""
|
||||
}</button>
|
||||
<input id="apiKey" style="margin-top: 8px; width: 100%; height:40px; box-sizing: border-box; padding: 0px 6px;" type="password" value="${data.apiKey
|
||||
<input id="apiKey" style="margin-top: 8px; width: 100%; height:40px; box-sizing: border-box; padding: 0px 6px;" type="password" value="${
|
||||
data.apiKey
|
||||
}">
|
||||
<button id="loginButton" style="margin-top: 8px; width: 100%; height:40px; box-sizing: border-box; padding: 0px 6px;">
|
||||
${data.apiKey ? "Re-login with ComfyDeploy" : "Login with ComfyDeploy"
|
||||
${
|
||||
data.apiKey ? "Re-login with ComfyDeploy" : "Login with ComfyDeploy"
|
||||
}
|
||||
</button>
|
||||
</div>
|
||||
@@ -1192,3 +1367,118 @@ export class ConfigDialog extends ComfyDialog {
|
||||
}
|
||||
|
||||
export const configDialog = new ConfigDialog();
|
||||
|
||||
const currentOrigin = window.location.origin;
|
||||
const client = new ComfyDeploy({
|
||||
bearerAuth: getData().apiKey,
|
||||
serverURL: `${currentOrigin}/comfydeploy/api/`,
|
||||
});
|
||||
|
||||
app.extensionManager.registerSidebarTab({
|
||||
id: "search",
|
||||
icon: "pi pi-cloud-upload",
|
||||
title: "Deploy",
|
||||
tooltip: "Deploy and Configure",
|
||||
type: "custom",
|
||||
render: (el) => {
|
||||
el.innerHTML = `
|
||||
<div style="padding: 20px;">
|
||||
<h3>Comfy Deploy</h3>
|
||||
<div id="deploy-container" style="margin-bottom: 20px;"></div>
|
||||
<div id="workflows-container">
|
||||
<h4>Your Workflows</h4>
|
||||
<div id="workflows-loading" style="display: flex; justify-content: center; align-items: center; height: 100px;">
|
||||
${loadingIcon}
|
||||
</div>
|
||||
<ul id="workflows-list" style="list-style-type: none; padding: 0; display: none;"></ul>
|
||||
</div>
|
||||
<div id="config-container"></div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
// Add deploy button
|
||||
const deployContainer = el.querySelector("#deploy-container");
|
||||
const deployButton = document.createElement("button");
|
||||
deployButton.id = "sidebar-deploy-button";
|
||||
deployButton.style.display = "flex";
|
||||
deployButton.style.alignItems = "center";
|
||||
deployButton.style.justifyContent = "center";
|
||||
deployButton.style.width = "100%";
|
||||
deployButton.style.marginBottom = "10px";
|
||||
deployButton.style.padding = "10px";
|
||||
deployButton.style.fontSize = "16px";
|
||||
deployButton.style.fontWeight = "bold";
|
||||
deployButton.style.backgroundColor = "#4CAF50";
|
||||
deployButton.style.color = "white";
|
||||
deployButton.style.border = "none";
|
||||
deployButton.style.borderRadius = "5px";
|
||||
deployButton.style.cursor = "pointer";
|
||||
deployButton.innerHTML = `<i class="pi pi-cloud-upload" style="margin-right: 8px;"></i><div id='sidebar-button-title'>Deploy</div>`;
|
||||
deployButton.onclick = async () => {
|
||||
await deployWorkflow();
|
||||
// Refresh the workflows list after deployment
|
||||
refreshWorkflowsList(el);
|
||||
};
|
||||
deployContainer.appendChild(deployButton);
|
||||
|
||||
// Add config button
|
||||
const configContainer = el.querySelector("#config-container");
|
||||
const configButton = document.createElement("button");
|
||||
configButton.style.display = "flex";
|
||||
configButton.style.alignItems = "center";
|
||||
configButton.style.justifyContent = "center";
|
||||
configButton.style.width = "100%";
|
||||
configButton.style.padding = "8px";
|
||||
configButton.style.fontSize = "14px";
|
||||
configButton.style.backgroundColor = "#f0f0f0";
|
||||
configButton.style.color = "#333";
|
||||
configButton.style.border = "1px solid #ccc";
|
||||
configButton.style.borderRadius = "5px";
|
||||
configButton.style.cursor = "pointer";
|
||||
configButton.innerHTML = `<i class="pi pi-cog" style="margin-right: 8px;"></i>Configure`;
|
||||
configButton.onclick = () => {
|
||||
configDialog.show();
|
||||
};
|
||||
deployContainer.appendChild(configButton);
|
||||
|
||||
// Fetch and display workflows
|
||||
const workflowsList = el.querySelector("#workflows-list");
|
||||
const workflowsLoading = el.querySelector("#workflows-loading");
|
||||
|
||||
refreshWorkflowsList(el);
|
||||
},
|
||||
});
|
||||
|
||||
function getTimeAgo(date) {
|
||||
const seconds = Math.floor((new Date() - date) / 1000);
|
||||
let interval = seconds / 31536000;
|
||||
if (interval > 1) return Math.floor(interval) + " years ago";
|
||||
interval = seconds / 2592000;
|
||||
if (interval > 1) return Math.floor(interval) + " months ago";
|
||||
interval = seconds / 86400;
|
||||
if (interval > 1) return Math.floor(interval) + " days ago";
|
||||
interval = seconds / 3600;
|
||||
if (interval > 1) return Math.floor(interval) + " hours ago";
|
||||
interval = seconds / 60;
|
||||
if (interval > 1) return Math.floor(interval) + " minutes ago";
|
||||
return Math.floor(seconds) + " seconds ago";
|
||||
}
|
||||
|
||||
async function loadWorkflowApi(versionId) {
|
||||
try {
|
||||
const response = await client.comfyui.getWorkflowVersionVersionId({
|
||||
versionId: versionId,
|
||||
});
|
||||
// Implement the logic to load the workflow API into the ComfyUI interface
|
||||
console.log("Workflow API loaded:", response);
|
||||
await window["app"].ui.settings.setSettingValueAsync(
|
||||
"Comfy.Validation.Workflows",
|
||||
false,
|
||||
);
|
||||
app.loadGraphData(response.workflow);
|
||||
// You might want to update the UI or trigger some action in ComfyUI here
|
||||
} catch (error) {
|
||||
console.error("Error loading workflow API:", error);
|
||||
// Show an error message to the user
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,7 +51,9 @@ const createRunRoute = createRoute({
|
||||
export const registerCreateRunRoute = (app: App) => {
|
||||
app.openapi(createRunRoute, async (c) => {
|
||||
const data = c.req.valid("json");
|
||||
const origin = new URL(c.req.url).origin;
|
||||
const proto = c.req.headers.get('x-forwarded-proto') || "http";
|
||||
const host = c.req.headers.get('x-forwarded-host') || c.req.headers.get('host');
|
||||
const origin = `${proto}://${host}` || new URL(c.req.url).origin;
|
||||
const apiKeyTokenData = c.get("apiKeyTokenData")!;
|
||||
|
||||
const { deployment_id, inputs } = data;
|
||||
|
||||
Reference in New Issue
Block a user