Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fd150aa20f | ||
|
|
17653508c5 | ||
|
|
ace12efd1a | ||
|
|
01e8668d1a | ||
|
|
8e58d962a7 | ||
|
|
c59c308d32 | ||
|
|
4560f2cca9 | ||
|
|
872752b820 | ||
|
|
97bb2b69c5 | ||
|
|
08fe87c8af | ||
|
|
d43e5fcefc | ||
|
|
65492a108c | ||
|
|
1939ff4153 | ||
|
|
4c32248d86 | ||
|
|
5ddbfdf44b | ||
|
|
7e86c20383 | ||
|
|
3adf77617b | ||
|
|
1bc62a5fb4 | ||
|
|
d473a211d0 | ||
|
|
3aa239e58d | ||
|
|
223aa5e70b | ||
|
|
5eef60a4eb | ||
|
|
de750995cb | ||
|
|
0f58fbcebd | ||
|
|
6dc964c425 | ||
|
|
4171c08413 | ||
|
|
4348ab45dc | ||
|
|
df46e3a0e5 | ||
|
|
2772101bbf | ||
|
|
72fee51d32 | ||
|
|
ffe0f98360 | ||
|
|
68377a84bc | ||
|
|
50d4c399e9 | ||
|
|
5a3955dfcb | ||
|
|
03227b52c0 | ||
|
|
8a8fbccfaa | ||
|
|
018d9a7b8d | ||
|
|
774fd566d1 | ||
|
|
b81fcae6fb | ||
|
|
b6b34c9062 | ||
|
|
f73baa091a | ||
|
|
a838cb7ad4 | ||
|
|
2afcade4f2 | ||
|
|
d70333baa6 | ||
|
|
43cfebd97a |
@@ -4,4 +4,15 @@ FROM mcr.microsoft.com/vscode/devcontainers/typescript-node:${VARIANT}
|
||||
# RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \
|
||||
# && apt-get -y install --no-install-recommends <your-package-list-here>
|
||||
|
||||
WORKDIR "/"
|
||||
|
||||
# Install fly
|
||||
RUN curl -L https://fly.io/install.sh | sh
|
||||
|
||||
ENV FLYCTL_INSTALL="/root/.fly"
|
||||
ENV PATH="$FLYCTL_INSTALL/bin:$PATH"
|
||||
|
||||
# RUN echo 'export FLYCTL_INSTALL="/home/node/.fly"' >> ~/.bashrc
|
||||
# RUN echo 'export PATH="$FLYCTL_INSTALL/bin:$PATH"' >> ~/.bashrc
|
||||
|
||||
RUN npm install -g bun
|
||||
@@ -4,6 +4,7 @@
|
||||
"service": "app",
|
||||
"workspaceFolder": "/workspaces/${localWorkspaceFolderBasename}",
|
||||
"postCreateCommand": "cd web && bun install && bun run migrate-local",
|
||||
"remoteUser": "root",
|
||||
"customizations": {
|
||||
"vscode": {
|
||||
"extensions": [
|
||||
@@ -13,7 +14,8 @@
|
||||
"stivo.tailwind-fold",
|
||||
"streetsidesoftware.code-spell-checker",
|
||||
"GitHub.copilot",
|
||||
"ms-azuretools.vscode-docker"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -75,10 +75,11 @@ Major areas
|
||||
3. `bun i`
|
||||
4. Start docker
|
||||
5. `cp .env.example .env.local`
|
||||
6. Repace `JWT_SECRET` with `openssl rand -hex 32`
|
||||
6. Replace `JWT_SECRET` with `openssl rand -hex 32`
|
||||
7. Get a local clerk dev key for `NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY` and `CLERK_SECRET_KEY`
|
||||
8. Keep a terminal live for `bun run db-dev`
|
||||
9. Finally start the next server with `bun dev`
|
||||
9. Execute the local migration to create the initial data `bun run migrate-local`
|
||||
10. Finally start the next server with `bun dev`
|
||||
|
||||
**Schema Changes**
|
||||
|
||||
@@ -92,6 +93,10 @@ Major areas
|
||||
|
||||
# Self Hosting with Vercel
|
||||
|
||||
[](https://www.youtube.com/watch?v=hWvsEY1cS2M)
|
||||
Tutorial Created by [Ross](https://github.com/rossman22590) and [Syn](https://github.com/mortlsyn)
|
||||
|
||||
|
||||
Build command
|
||||
|
||||
```
|
||||
|
||||
@@ -312,7 +312,8 @@ async def build_logic(item: Item):
|
||||
config = {
|
||||
"name": item.name,
|
||||
"deploy_test": os.environ.get("DEPLOY_TEST_FLAG", "False"),
|
||||
"gpu": item.gpu
|
||||
"gpu": item.gpu,
|
||||
"civitai_token": os.environ.get("CIVITAI_TOKEN", "")
|
||||
}
|
||||
with open(f"{folder_path}/config.py", "w") as f:
|
||||
f.write("config = " + json.dumps(config))
|
||||
|
||||
@@ -36,6 +36,9 @@ if not deploy_test:
|
||||
|
||||
dockerfile_image = (
|
||||
modal.Image.debian_slim()
|
||||
.env({
|
||||
"CIVITAI_TOKEN": config["civitai_token"],
|
||||
})
|
||||
.apt_install("git", "wget")
|
||||
.pip_install(
|
||||
"git+https://github.com/modal-labs/asgiproxy.git", "httpx", "tqdm"
|
||||
@@ -231,7 +234,8 @@ def run(input: Input):
|
||||
async def bar(request_input: RequestInput):
|
||||
# print(request_input)
|
||||
if not deploy_test:
|
||||
return run.remote(request_input.input)
|
||||
run.spawn(request_input.input)
|
||||
return {"status": "success"}
|
||||
# pass
|
||||
|
||||
|
||||
|
||||
@@ -49,6 +49,12 @@ with open('models.json') as f:
|
||||
models = json.load(f)
|
||||
|
||||
for model in models:
|
||||
import os
|
||||
if "civitai.com/api" in model['url'] and not "token=" in model['url']:
|
||||
if "?" in model['url']:
|
||||
model['url'] += "&token=" + os.environ.get('CIVITAI_TOKEN', '')
|
||||
else:
|
||||
model['url'] += "?token=" + os.environ.get('CIVITAI_TOKEN', '')
|
||||
response = requests.request("POST", f"{root_url}/model/install", json=model, headers=headers)
|
||||
print(response.text)
|
||||
|
||||
|
||||
@@ -29,9 +29,7 @@ class ComfyUIDeployExternalText:
|
||||
CATEGORY = "text"
|
||||
|
||||
def run(self, input_id, default_value=None):
|
||||
if not input_id or len(input_id.strip()) == 0:
|
||||
return [default_value]
|
||||
return [input_id]
|
||||
return [default_value]
|
||||
|
||||
|
||||
NODE_CLASS_MAPPINGS = {"ComfyUIDeployExternalText": ComfyUIDeployExternalText}
|
||||
|
||||
@@ -22,10 +22,14 @@ from logging.handlers import RotatingFileHandler
|
||||
from enum import Enum
|
||||
from urllib.parse import quote
|
||||
import threading
|
||||
import hashlib
|
||||
import aiohttp
|
||||
|
||||
api = None
|
||||
api_task = None
|
||||
prompt_metadata = {}
|
||||
cd_enable_log = os.environ.get('CD_ENABLE_LOG', 'false').lower() == 'true'
|
||||
cd_enable_run_log = os.environ.get('CD_ENABLE_RUN_LOG', 'false').lower() == 'true'
|
||||
|
||||
def post_prompt(json_data):
|
||||
prompt_server = server.PromptServer.instance
|
||||
@@ -97,6 +101,7 @@ async def comfy_deploy_run(request):
|
||||
prompt_metadata[prompt_id] = {
|
||||
'status_endpoint': data.get('status_endpoint'),
|
||||
'file_upload_endpoint': data.get('file_upload_endpoint'),
|
||||
'workflow_api': workflow_api
|
||||
}
|
||||
|
||||
try:
|
||||
@@ -113,6 +118,8 @@ async def comfy_deploy_run(request):
|
||||
"stack_trace": stack_trace
|
||||
}
|
||||
})
|
||||
# When there are critical errors, the prompt is actually not run
|
||||
await update_run(prompt_id, Status.FAILED)
|
||||
return web.Response(status=500, reason=f"{error_type}: {e}, {stack_trace_short}")
|
||||
|
||||
status = 200
|
||||
@@ -141,6 +148,138 @@ async def comfy_deploy_run(request):
|
||||
|
||||
sockets = dict()
|
||||
|
||||
def get_comfyui_path_from_file_path(file_path):
|
||||
file_path_parts = file_path.split("\\")
|
||||
|
||||
if file_path_parts[0] == "input":
|
||||
print("matching input")
|
||||
file_path = os.path.join(folder_paths.get_directory_by_type("input"), *file_path_parts[1:])
|
||||
elif file_path_parts[0] == "models":
|
||||
print("matching models")
|
||||
file_path = folder_paths.get_full_path(file_path_parts[1], os.path.join(*file_path_parts[2:]))
|
||||
|
||||
print(file_path)
|
||||
|
||||
return file_path
|
||||
|
||||
# Form ComfyUI Manager
|
||||
def compute_sha256_checksum(filepath):
|
||||
filepath = get_comfyui_path_from_file_path(filepath)
|
||||
"""Compute the SHA256 checksum of a file, in chunks"""
|
||||
sha256 = hashlib.sha256()
|
||||
with open(filepath, 'rb') as f:
|
||||
for chunk in iter(lambda: f.read(4096), b''):
|
||||
sha256.update(chunk)
|
||||
return sha256.hexdigest()
|
||||
|
||||
# This is start uploading the files to Comfy Deploy
|
||||
@server.PromptServer.instance.routes.post('/comfyui-deploy/upload-file')
|
||||
async def upload_file(request):
|
||||
data = await request.json()
|
||||
|
||||
file_path = data.get("file_path")
|
||||
|
||||
print("Original file path", file_path)
|
||||
|
||||
file_path = get_comfyui_path_from_file_path(file_path)
|
||||
|
||||
# return web.json_response({
|
||||
# "error": f"File not uploaded"
|
||||
# }, status=500)
|
||||
|
||||
token = data.get("token")
|
||||
get_url = data.get("url")
|
||||
|
||||
try:
|
||||
base = folder_paths.base_path
|
||||
file_path = os.path.join(base, file_path)
|
||||
|
||||
if os.path.exists(file_path):
|
||||
file_size = os.path.getsize(file_path)
|
||||
file_extension = os.path.splitext(file_path)[1]
|
||||
|
||||
if file_extension in ['.jpg', '.jpeg']:
|
||||
file_type = 'image/jpeg'
|
||||
elif file_extension == '.png':
|
||||
file_type = 'image/png'
|
||||
elif file_extension == '.webp':
|
||||
file_type = 'image/webp'
|
||||
else:
|
||||
file_type = 'application/octet-stream' # Default to binary file type if unknown
|
||||
else:
|
||||
return web.json_response({
|
||||
"error": f"File not found: {file_path}"
|
||||
}, status=404)
|
||||
|
||||
except Exception as e:
|
||||
return web.json_response({
|
||||
"error": str(e)
|
||||
}, status=500)
|
||||
|
||||
if get_url:
|
||||
try:
|
||||
async with aiohttp.ClientSession() as session:
|
||||
headers = {'Authorization': f'Bearer {token}'}
|
||||
params = {'file_size': file_size, 'type': file_type}
|
||||
async with session.get(get_url, params=params, headers=headers) as response:
|
||||
if response.status == 200:
|
||||
content = await response.json()
|
||||
upload_url = content["upload_url"]
|
||||
|
||||
with open(file_path, 'rb') as f:
|
||||
headers = {
|
||||
"Content-Type": file_type,
|
||||
"x-amz-acl": "public-read",
|
||||
"Content-Length": str(file_size)
|
||||
}
|
||||
async with session.put(upload_url, data=f, headers=headers) as upload_response:
|
||||
if upload_response.status == 200:
|
||||
return web.json_response({
|
||||
"message": "File uploaded successfully",
|
||||
"download_url": content["download_url"]
|
||||
})
|
||||
else:
|
||||
return web.json_response({
|
||||
"error": f"Failed to upload file to {upload_url}. Status code: {upload_response.status}"
|
||||
}, status=upload_response.status)
|
||||
else:
|
||||
return web.json_response({
|
||||
"error": f"Failed to fetch data from {get_url}. Status code: {response.status}"
|
||||
}, status=response.status)
|
||||
except Exception as e:
|
||||
return web.json_response({
|
||||
"error": f"An error occurred while fetching data from {get_url}: {str(e)}"
|
||||
}, status=500)
|
||||
|
||||
return web.json_response({
|
||||
"error": f"File not uploaded"
|
||||
}, status=500)
|
||||
|
||||
|
||||
@server.PromptServer.instance.routes.get('/comfyui-deploy/get-file-hash')
|
||||
async def get_file_hash(request):
|
||||
file_path = request.rel_url.query.get('file_path', '')
|
||||
|
||||
if file_path is None:
|
||||
return web.json_response({
|
||||
"error": "file_path is required"
|
||||
}, status=400)
|
||||
|
||||
try:
|
||||
base = folder_paths.base_path
|
||||
file_path = os.path.join(base, file_path)
|
||||
# print("file_path", file_path)
|
||||
file_hash = compute_sha256_checksum(
|
||||
file_path
|
||||
)
|
||||
return web.json_response({
|
||||
"file_hash": file_hash
|
||||
})
|
||||
except Exception as e:
|
||||
return web.json_response({
|
||||
"error": str(e)
|
||||
}, status=500)
|
||||
|
||||
@server.PromptServer.instance.routes.get('/comfyui-deploy/ws')
|
||||
async def websocket_handler(request):
|
||||
ws = web.WebSocketResponse()
|
||||
@@ -157,7 +296,9 @@ async def websocket_handler(request):
|
||||
try:
|
||||
# Send initial state to the new client
|
||||
await send("status", { 'sid': sid }, sid)
|
||||
await send_first_time_log(sid)
|
||||
|
||||
if cd_enable_log:
|
||||
await send_first_time_log(sid)
|
||||
|
||||
async for msg in ws:
|
||||
if msg.type == aiohttp.WSMsgType.ERROR:
|
||||
@@ -217,6 +358,34 @@ async def send_json_override(self, event, data, sid=None):
|
||||
if not have_pending_upload(prompt_id):
|
||||
update_run(prompt_id, Status.SUCCESS)
|
||||
|
||||
if event == 'executing' and data.get('node') is not None:
|
||||
node = data.get('node')
|
||||
|
||||
if prompt_id in prompt_metadata:
|
||||
if 'progress' not in prompt_metadata[prompt_id]:
|
||||
prompt_metadata[prompt_id]["progress"] = set()
|
||||
|
||||
prompt_metadata[prompt_id]["progress"].add(node)
|
||||
calculated_progress = len(prompt_metadata[prompt_id]["progress"]) / len(prompt_metadata[prompt_id]['workflow_api'])
|
||||
# print("calculated_progress", calculated_progress)
|
||||
|
||||
if 'last_updated_node' in prompt_metadata[prompt_id] and prompt_metadata[prompt_id]['last_updated_node'] == node:
|
||||
return
|
||||
prompt_metadata[prompt_id]['last_updated_node'] = node
|
||||
class_type = prompt_metadata[prompt_id]['workflow_api'][node]['class_type']
|
||||
print("updating run live status", class_type)
|
||||
await update_run_live_status(prompt_id, "Executing " + class_type, calculated_progress)
|
||||
|
||||
if event == 'execution_cached' and data.get('nodes') is not None:
|
||||
if prompt_id in prompt_metadata:
|
||||
if 'progress' not in prompt_metadata[prompt_id]:
|
||||
prompt_metadata[prompt_id]["progress"] = set()
|
||||
|
||||
if 'nodes' in data:
|
||||
for node in data.get('nodes', []):
|
||||
prompt_metadata[prompt_id]["progress"].add(node)
|
||||
# prompt_metadata[prompt_id]["progress"].update(data.get('nodes'))
|
||||
|
||||
if event == 'execution_error':
|
||||
# Careful this might not be fully awaited.
|
||||
await update_run_with_output(prompt_id, data)
|
||||
@@ -236,7 +405,30 @@ class Status(Enum):
|
||||
FAILED = "failed"
|
||||
UPLOADING = "uploading"
|
||||
|
||||
# Global variable to keep track of the last read line number
|
||||
last_read_line_number = 0
|
||||
|
||||
async def update_run_live_status(prompt_id, live_status, calculated_progress: float):
|
||||
if prompt_id not in prompt_metadata:
|
||||
return
|
||||
|
||||
print("progress", calculated_progress)
|
||||
|
||||
status_endpoint = prompt_metadata[prompt_id]['status_endpoint']
|
||||
body = {
|
||||
"run_id": prompt_id,
|
||||
"live_status": live_status,
|
||||
"progress": calculated_progress
|
||||
}
|
||||
# requests.post(status_endpoint, json=body)
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.post(status_endpoint, json=body) as response:
|
||||
pass
|
||||
|
||||
|
||||
def update_run(prompt_id, status: Status):
|
||||
global last_read_line_number
|
||||
|
||||
if prompt_id not in prompt_metadata:
|
||||
return
|
||||
|
||||
@@ -251,16 +443,50 @@ def update_run(prompt_id, status: Status):
|
||||
"run_id": prompt_id,
|
||||
"status": status.value,
|
||||
}
|
||||
prompt_metadata[prompt_id]['status'] = status
|
||||
print(f"Status: {status.value}")
|
||||
|
||||
try:
|
||||
requests.post(status_endpoint, json=body)
|
||||
|
||||
if cd_enable_run_log and (status == Status.SUCCESS or status == Status.FAILED):
|
||||
try:
|
||||
with open(comfyui_file_path, 'r') as log_file:
|
||||
# log_data = log_file.read()
|
||||
# Move to the last read line
|
||||
all_log_data = log_file.read() # Read all log data
|
||||
print("All log data before skipping:", all_log_data) # Log all data before skipping
|
||||
log_file.seek(0) # Reset file pointer to the beginning
|
||||
|
||||
for _ in range(last_read_line_number):
|
||||
next(log_file)
|
||||
log_data = log_file.read()
|
||||
# Update the last read line number
|
||||
last_read_line_number += log_data.count('\n')
|
||||
print("last_read_line_number", last_read_line_number)
|
||||
print("log_data", log_data)
|
||||
print("log_data.count(n)", log_data.count('\n'))
|
||||
|
||||
body = {
|
||||
"run_id": prompt_id,
|
||||
"log_data": [
|
||||
{
|
||||
"logs": log_data,
|
||||
# "timestamp": time.time(),
|
||||
}
|
||||
]
|
||||
}
|
||||
requests.post(status_endpoint, json=body)
|
||||
except Exception as log_error:
|
||||
print(f"Error reading log file: {log_error}")
|
||||
|
||||
|
||||
except Exception as e:
|
||||
error_type = type(e).__name__
|
||||
stack_trace = traceback.format_exc().strip()
|
||||
print(f"Error occurred while updating run: {e} {stack_trace}")
|
||||
|
||||
finally:
|
||||
prompt_metadata[prompt_id]['status'] = status
|
||||
|
||||
|
||||
async def upload_file(prompt_id, filename, subfolder=None, content_type="image/png", type="output"):
|
||||
"""
|
||||
@@ -310,7 +536,9 @@ async def upload_file(prompt_id, filename, subfolder=None, content_type="image/p
|
||||
"Content-Length": str(len(data)),
|
||||
}
|
||||
response = requests.put(ok.get("url"), headers=headers, data=data)
|
||||
print("upload file response", response.status_code)
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.put(ok.get("url"), headers=headers, data=data) as response:
|
||||
print("upload file response", response.status)
|
||||
|
||||
def have_pending_upload(prompt_id):
|
||||
if 'prompt_id' in prompt_metadata and 'uploading_nodes' in prompt_metadata[prompt_id] and len(prompt_metadata[prompt_id]['uploading_nodes']) > 0:
|
||||
@@ -387,20 +615,25 @@ async def update_file_status(prompt_id, data, uploading, have_error=False, node_
|
||||
"prompt_id": prompt_id,
|
||||
})
|
||||
|
||||
async def handle_upload(prompt_id, data, key, content_type_key, default_content_type):
|
||||
items = data.get(key, [])
|
||||
for item in items:
|
||||
await upload_file(
|
||||
prompt_id,
|
||||
item.get("filename"),
|
||||
subfolder=item.get("subfolder"),
|
||||
type=item.get("type"),
|
||||
content_type=item.get(content_type_key, default_content_type)
|
||||
)
|
||||
|
||||
|
||||
# Upload files in the background
|
||||
async def upload_in_background(prompt_id, data, node_id=None, have_upload=True):
|
||||
try:
|
||||
images = data.get('images', [])
|
||||
for image in images:
|
||||
await upload_file(prompt_id, image.get("filename"), subfolder=image.get("subfolder"), type=image.get("type"), content_type=image.get("content_type", "image/png"))
|
||||
|
||||
files = data.get('files', [])
|
||||
for file in files:
|
||||
await upload_file(prompt_id, file.get("filename"), subfolder=file.get("subfolder"), type=file.get("type"), content_type=file.get("content_type", "image/png"))
|
||||
|
||||
gifs = data.get('gifs', [])
|
||||
for gif in gifs:
|
||||
await upload_file(prompt_id, gif.get("filename"), subfolder=gif.get("subfolder"), type=gif.get("type"), content_type=gif.get("format", "image/gif"))
|
||||
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")
|
||||
|
||||
if have_upload:
|
||||
await update_file_status(prompt_id, data, False, node_id=node_id)
|
||||
@@ -441,6 +674,7 @@ prompt_server.send_json = send_json_override.__get__(prompt_server, server.Promp
|
||||
root_path = os.path.dirname(os.path.abspath(__file__))
|
||||
two_dirs_up = os.path.dirname(os.path.dirname(root_path))
|
||||
log_file_path = os.path.join(two_dirs_up, 'comfy-deploy.log')
|
||||
comfyui_file_path = os.path.join(two_dirs_up, 'comfyui.log')
|
||||
|
||||
last_read_line = 0
|
||||
|
||||
@@ -480,4 +714,5 @@ def run_in_new_thread(coroutine):
|
||||
t.start()
|
||||
asyncio.run_coroutine_threadsafe(coroutine, new_loop)
|
||||
|
||||
run_in_new_thread(watch_file_changes(log_file_path, send_logs_to_websocket))
|
||||
if cd_enable_log:
|
||||
run_in_new_thread(watch_file_changes(log_file_path, send_logs_to_websocket))
|
||||
|
||||
@@ -7,45 +7,56 @@ import threading
|
||||
import logging
|
||||
from logging.handlers import RotatingFileHandler
|
||||
|
||||
handler = RotatingFileHandler('comfy-deploy.log', maxBytes=500000, backupCount=5)
|
||||
# Running with export CD_ENABLE_LOG=true; python main.py
|
||||
|
||||
original_stdout = sys.stdout
|
||||
original_stderr = sys.stderr
|
||||
# Check for 'cd-enable-log' flag in input arguments
|
||||
# cd_enable_log = '--cd-enable-log' in sys.argv
|
||||
cd_enable_log = os.environ.get('CD_ENABLE_LOG', 'false').lower() == 'true'
|
||||
|
||||
class StreamToLogger():
|
||||
def __init__(self, log_level):
|
||||
self.log_level = log_level
|
||||
def setup():
|
||||
handler = RotatingFileHandler('comfy-deploy.log', maxBytes=500000, backupCount=5)
|
||||
|
||||
def write(self, buf):
|
||||
if (self.log_level == logging.INFO):
|
||||
original_stdout.write(buf)
|
||||
original_stdout.flush()
|
||||
elif (self.log_level == logging.ERROR):
|
||||
original_stderr.write(buf)
|
||||
original_stderr.flush()
|
||||
original_stdout = sys.stdout
|
||||
original_stderr = sys.stderr
|
||||
|
||||
for line in buf.rstrip().splitlines():
|
||||
handler.handle(
|
||||
logging.LogRecord(
|
||||
name="comfy-deploy",
|
||||
level=self.log_level,
|
||||
pathname="prestartup_script.py",
|
||||
lineno=1,
|
||||
msg=line.rstrip(),
|
||||
args=None,
|
||||
exc_info=None
|
||||
class StreamToLogger():
|
||||
def __init__(self, log_level):
|
||||
self.log_level = log_level
|
||||
|
||||
def write(self, buf):
|
||||
if (self.log_level == logging.INFO):
|
||||
original_stdout.write(buf)
|
||||
original_stdout.flush()
|
||||
elif (self.log_level == logging.ERROR):
|
||||
original_stderr.write(buf)
|
||||
original_stderr.flush()
|
||||
|
||||
for line in buf.rstrip().splitlines():
|
||||
handler.handle(
|
||||
logging.LogRecord(
|
||||
name="comfy-deploy",
|
||||
level=self.log_level,
|
||||
pathname="prestartup_script.py",
|
||||
lineno=1,
|
||||
msg=line.rstrip(),
|
||||
args=None,
|
||||
exc_info=None
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
def flush(self):
|
||||
if (self.log_level == logging.INFO):
|
||||
original_stdout.flush()
|
||||
elif (self.log_level == logging.ERROR):
|
||||
original_stderr.flush()
|
||||
def flush(self):
|
||||
if (self.log_level == logging.INFO):
|
||||
original_stdout.flush()
|
||||
elif (self.log_level == logging.ERROR):
|
||||
original_stderr.flush()
|
||||
|
||||
# Redirect stdout and stderr to the logger
|
||||
sys.stdout = StreamToLogger(logging.INFO)
|
||||
sys.stderr = StreamToLogger(logging.ERROR)
|
||||
# Redirect stdout and stderr to the logger
|
||||
sys.stdout = StreamToLogger(logging.INFO)
|
||||
sys.stderr = StreamToLogger(logging.ERROR)
|
||||
|
||||
if cd_enable_log:
|
||||
print("** Comfy Deploy logging enabled")
|
||||
setup()
|
||||
|
||||
try:
|
||||
# Get the absolute path of the script's directory
|
||||
|
||||
@@ -1,6 +1,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]";
|
||||
|
||||
/** @typedef {import('../../../web/types/comfy.js').ComfyExtension} ComfyExtension*/
|
||||
/** @type {ComfyExtension} */
|
||||
@@ -15,27 +16,28 @@ const ext = {
|
||||
const auth_token = queryParams.get("auth_token");
|
||||
const org_display = queryParams.get("org_display");
|
||||
const origin = queryParams.get("origin");
|
||||
|
||||
const data = getData();
|
||||
let endpoint = data.endpoint;
|
||||
let apiKey = data.apiKey;
|
||||
|
||||
// If there is auth token override it
|
||||
if (auth_token) {
|
||||
apiKey = auth_token;
|
||||
endpoint = origin;
|
||||
saveData({
|
||||
displayName: org_display,
|
||||
endpoint: origin,
|
||||
apiKey: auth_token,
|
||||
displayName: org_display,
|
||||
environment: "cloud",
|
||||
});
|
||||
localStorage.setItem("comfy_deploy_env", "cloud");
|
||||
}
|
||||
|
||||
if (!workflow_version_id) {
|
||||
console.error("No workflow_version_id provided in query parameters.");
|
||||
} else {
|
||||
const data = getData();
|
||||
let endpoint = data.endpoint;
|
||||
let apiKey = data.apiKey;
|
||||
|
||||
// If there is auth token override it
|
||||
if (auth_token) {
|
||||
apiKey = auth_token;
|
||||
endpoint = origin;
|
||||
saveData({
|
||||
displayName: org_display,
|
||||
endpoint: origin,
|
||||
apiKey: auth_token,
|
||||
displayName: org_display,
|
||||
environment: "cloud",
|
||||
});
|
||||
localStorage.setItem("comfy_deploy_env", "cloud");
|
||||
}
|
||||
|
||||
loadingDialog.showLoading(
|
||||
"Loading workflow from " + org_display,
|
||||
"Please wait...",
|
||||
@@ -49,11 +51,22 @@ const ext = {
|
||||
})
|
||||
.then(async (res) => {
|
||||
const data = await res.json();
|
||||
const { workflow, error } = data;
|
||||
const { workflow, workflow_id, error } = data;
|
||||
if (error) {
|
||||
infoDialog.showMessage("Unable to load this workflow", error);
|
||||
return;
|
||||
}
|
||||
|
||||
// Adding a delay to wait for the intial graph to load
|
||||
await new Promise((resolve) => setTimeout(resolve, 2000));
|
||||
|
||||
workflow?.nodes.forEach((x) => {
|
||||
if (x?.type === "ComfyDeploy") {
|
||||
x.widgets_values[1] = workflow_id;
|
||||
// x.widgets_values[2] = workflow_version.version;
|
||||
}
|
||||
});
|
||||
|
||||
/** @type {LGraph} */
|
||||
app.loadGraphData(workflow);
|
||||
})
|
||||
@@ -166,6 +179,92 @@ function showError(title, message) {
|
||||
);
|
||||
}
|
||||
|
||||
function createDynamicUIHtml(data) {
|
||||
console.log(data);
|
||||
let html =
|
||||
'<div style="min-width: 600px; max-width: 1024px; margin: 14px auto; display: flex; flex-direction: column; gap: 24px;">';
|
||||
const bgcolor = "var(--comfy-input-bg)";
|
||||
const evenBg = "var(--border-color)";
|
||||
const textColor = "var(--input-text)";
|
||||
|
||||
// Custom Nodes
|
||||
html += `<div style="background-color: ${bgcolor}; padding: 24px; border-radius: 8px; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);">`;
|
||||
html +=
|
||||
'<h2 style="margin-top: 0px; font-size: 24px; font-weight: bold; margin-bottom: 16px;">Custom Nodes</h2>';
|
||||
|
||||
if (data.missing_nodes?.length > 0) {
|
||||
html += `
|
||||
<div style="border-bottom: 1px solid #e2e8f0; padding: 4px 12px; background-color: ${evenBg}">
|
||||
<h3 style="font-size: 14px; font-weight: semibold; margin-bottom: 8px;">Missing Nodes</h3>
|
||||
<p style="font-size: 12px;">These nodes are not found with any matching custom_nodes in the ComfyUI Manager Database</p>
|
||||
${data.missing_nodes
|
||||
.map((node) => {
|
||||
return `<p style="font-size: 14px; color: #d69e2e;">${node}</p>`;
|
||||
})
|
||||
.join("")}
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
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>
|
||||
<p style="font-size: 14px; color: #4b5563;">${node.hash}</p>
|
||||
${
|
||||
node.warning
|
||||
? `<p style="font-size: 14px; color: #d69e2e;">${node.warning}</p>`
|
||||
: ""
|
||||
}
|
||||
</div>
|
||||
`;
|
||||
});
|
||||
html += "</div>";
|
||||
|
||||
// Models
|
||||
html += `<div style="background-color: ${bgcolor}; padding: 24px; border-radius: 8px; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);">`;
|
||||
html +=
|
||||
'<h2 style="margin-top: 0px; font-size: 24px; font-weight: bold; margin-bottom: 16px;">Models</h2>';
|
||||
|
||||
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>`;
|
||||
items.forEach((item) => {
|
||||
html += `<p style="font-size: 14px; color: ${textColor};">${item.name}</p>`;
|
||||
});
|
||||
html += "</div>";
|
||||
});
|
||||
html += "</div>";
|
||||
|
||||
// Models
|
||||
html += `<div style="background-color: ${bgcolor}; padding: 24px; border-radius: 8px; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);">`;
|
||||
html +=
|
||||
'<h2 style="margin-top: 0px; font-size: 24px; font-weight: bold; margin-bottom: 16px;">Files</h2>';
|
||||
|
||||
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>`;
|
||||
items.forEach((item) => {
|
||||
html += `<p style="font-size: 14px; color: ${textColor};">${item.name}</p>`;
|
||||
});
|
||||
html += "</div>";
|
||||
});
|
||||
html += "</div>";
|
||||
|
||||
html += "</div>";
|
||||
return html;
|
||||
}
|
||||
|
||||
function addButton() {
|
||||
const menu = document.querySelector(".comfy-menu");
|
||||
|
||||
@@ -177,8 +276,33 @@ function addButton() {
|
||||
/** @type {LGraph} */
|
||||
const graph = app.graph;
|
||||
|
||||
let { endpoint, apiKey, displayName } = getData();
|
||||
|
||||
if (!endpoint || !apiKey || apiKey === "" || endpoint === "") {
|
||||
configDialog.show();
|
||||
return;
|
||||
}
|
||||
|
||||
const ok = await confirmDialog.confirm(
|
||||
"Confirm deployment -> " +
|
||||
displayName +
|
||||
"<br><br><small><div style='font-weight: normal;'>" +
|
||||
endpoint +
|
||||
"<div><br>",
|
||||
`A new version will be deployed, are you confirm? <br><br><input id="include-deps" type="checkbox" checked>Include dependence</input>`,
|
||||
);
|
||||
if (!ok) return;
|
||||
|
||||
const includeDeps = document.getElementById("include-deps").checked;
|
||||
|
||||
if (endpoint.endsWith("/")) {
|
||||
endpoint = endpoint.slice(0, -1);
|
||||
}
|
||||
loadingDialog.showLoading("Generating snapshot", "Please wait...");
|
||||
|
||||
const snapshot = await fetch("/snapshot/get_current").then((x) => x.json());
|
||||
// console.log(snapshot);
|
||||
loadingDialog.close();
|
||||
|
||||
if (!snapshot) {
|
||||
showError(
|
||||
@@ -212,32 +336,94 @@ function addButton() {
|
||||
|
||||
const deployMetaNode = deployMeta[0];
|
||||
|
||||
// console.log(deployMetaNode);
|
||||
|
||||
const workflow_name = deployMetaNode.widgets[0].value;
|
||||
const workflow_id = deployMetaNode.widgets[1].value;
|
||||
|
||||
console.log(workflow_name, workflow_id);
|
||||
|
||||
const prompt = await app.graphToPrompt();
|
||||
console.log(graph);
|
||||
console.log(prompt);
|
||||
let deps = undefined;
|
||||
|
||||
// const endpoint = localStorage.getItem("endpoint") ?? "";
|
||||
// const apiKey = localStorage.getItem("apiKey");
|
||||
if (includeDeps) {
|
||||
loadingDialog.showLoading("Fetching existing version", "Please wait...");
|
||||
|
||||
const { endpoint, apiKey, displayName } = getData();
|
||||
const existing_workflow = await fetch(
|
||||
endpoint + "/api/workflow/" + workflow_id,
|
||||
{
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer " + apiKey,
|
||||
},
|
||||
},
|
||||
)
|
||||
.then((x) => x.json())
|
||||
.catch(() => {
|
||||
return {};
|
||||
});
|
||||
|
||||
if (!endpoint || !apiKey || apiKey === "" || endpoint === "") {
|
||||
configDialog.show();
|
||||
return;
|
||||
loadingDialog.close();
|
||||
|
||||
loadingDialog.showLoading(
|
||||
"Generating dependency graph",
|
||||
"Please wait...",
|
||||
);
|
||||
deps = await generateDependencyGraph({
|
||||
workflow_api: prompt.output,
|
||||
snapshot: snapshot,
|
||||
computeFileHash: async (file) => {
|
||||
console.log(file);
|
||||
loadingDialog.showLoading("Generating hash", file);
|
||||
const hash = await fetch(
|
||||
`/comfyui-deploy/get-file-hash?file_path=${encodeURIComponent(
|
||||
file,
|
||||
)}`,
|
||||
).then((x) => x.json());
|
||||
loadingDialog.showLoading("Generating hash", file);
|
||||
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;
|
||||
}
|
||||
},
|
||||
existingDependencies: existing_workflow.dependencies,
|
||||
});
|
||||
|
||||
loadingDialog.close();
|
||||
|
||||
const depsOk = await confirmDialog.confirm(
|
||||
"Check dependencies",
|
||||
// JSON.stringify(deps, null, 2),
|
||||
createDynamicUIHtml(deps),
|
||||
);
|
||||
if (!depsOk) return;
|
||||
|
||||
console.log(deps);
|
||||
}
|
||||
|
||||
const ok = await confirmDialog.confirm(
|
||||
"Confirm deployment -> " + displayName,
|
||||
"A new version will be deployed, are you conform?",
|
||||
);
|
||||
if (!ok) return;
|
||||
loadingDialog.showLoading("Deploying...");
|
||||
|
||||
title.innerText = "Deploying...";
|
||||
title.style.color = "orange";
|
||||
@@ -249,6 +435,8 @@ function addButton() {
|
||||
endpoint = endpoint.slice(0, -1);
|
||||
}
|
||||
|
||||
// console.log(prompt.workflow);
|
||||
|
||||
const apiRoute = endpoint + "/api/workflow";
|
||||
// const userId = apiKey
|
||||
try {
|
||||
@@ -258,6 +446,7 @@ function addButton() {
|
||||
workflow: prompt.workflow,
|
||||
workflow_api: prompt.output,
|
||||
snapshot: snapshot,
|
||||
dependencies: deps,
|
||||
};
|
||||
console.log(body);
|
||||
let data = await fetch(apiRoute, {
|
||||
@@ -277,6 +466,8 @@ function addButton() {
|
||||
data = await data.json();
|
||||
}
|
||||
|
||||
loadingDialog.close();
|
||||
|
||||
title.textContent = "Done";
|
||||
title.style.color = "green";
|
||||
|
||||
@@ -293,6 +484,7 @@ function addButton() {
|
||||
title.style.color = "white";
|
||||
}, 1000);
|
||||
} catch (e) {
|
||||
loadingDialog.close();
|
||||
app.ui.dialog.show(e);
|
||||
console.error(e);
|
||||
title.textContent = "Error";
|
||||
@@ -369,7 +561,7 @@ export class InfoDialog extends ComfyDialog {
|
||||
|
||||
showMessage(title, message) {
|
||||
this.show(`
|
||||
<div style="width: 400px; display: flex; gap: 18px; flex-direction: column; overflow: unset">
|
||||
<div style="width: 100%; max-width: 600px; display: flex; gap: 18px; flex-direction: column; overflow: unset">
|
||||
<h3 style="margin: 0px;">${title}</h3>
|
||||
<label>
|
||||
${message}
|
||||
@@ -425,7 +617,10 @@ 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: 4px;">${title} ${this.loadingIcon}</h3>
|
||||
<h3 style="margin: 0px; display: flex; align-items: center; justify-content: center; gap: 12px;">${title} ${
|
||||
this.loadingIcon
|
||||
}</h3>
|
||||
${message ? `<label>${message}</label>` : ""}
|
||||
</div>
|
||||
`);
|
||||
}
|
||||
@@ -544,7 +739,7 @@ export class ConfirmDialog extends InfoDialog {
|
||||
return new Promise((resolve, reject) => {
|
||||
this.callback = resolve;
|
||||
this.show(`
|
||||
<div style="width: 400px; display: flex; gap: 18px; flex-direction: column; overflow: unset">
|
||||
<div style="width: 100%; max-width: 600px; display: flex; gap: 18px; flex-direction: column; overflow: unset">
|
||||
<h3 style="margin: 0px;">${title}</h3>
|
||||
<label>
|
||||
${message}
|
||||
|
||||
|
After Width: | Height: | Size: 22 KiB |
|
After Width: | Height: | Size: 24 KiB |
|
After Width: | Height: | Size: 30 KiB |
|
After Width: | Height: | Size: 25 KiB |
|
After Width: | Height: | Size: 45 KiB |
|
After Width: | Height: | Size: 29 KiB |
|
After Width: | Height: | Size: 29 KiB |
@@ -0,0 +1,9 @@
|
||||
"use client";
|
||||
|
||||
import { LoadingPageWrapper } from "@/components/LoadingWrapper";
|
||||
import { usePathname } from "next/navigation";
|
||||
|
||||
export default function Loading() {
|
||||
const pathName = usePathname();
|
||||
return <LoadingPageWrapper className="h-full" tag={pathName.toLowerCase()} />;
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import Image from "next/image";
|
||||
import Link from "next/link";
|
||||
|
||||
export default function Page() {
|
||||
return <Examples />;
|
||||
}
|
||||
|
||||
|
||||
type exampleWorkflow = {
|
||||
title: string;
|
||||
description: string;
|
||||
previewURL: string;
|
||||
image: {
|
||||
src: string,
|
||||
alt: string,
|
||||
};
|
||||
};
|
||||
|
||||
const exampleWorkflows: exampleWorkflow[] = [
|
||||
{
|
||||
title: "Txt2Img SDXL",
|
||||
description: "The basic workflow, type a prompt and generate images based on that.",
|
||||
previewURL: 'https://www.comfydeploy.com/share/comfy-deploy-example-txt2img-sdxl',
|
||||
image: {
|
||||
src: '/example-workflows/txt2img.webp',
|
||||
alt: 'IPAdapter workflow',
|
||||
}
|
||||
},
|
||||
{
|
||||
title: "Txt2Img LCM SDXL",
|
||||
description: "Images in a couple of seconds, increase the speed of each generation using LCM Lora.",
|
||||
previewURL: 'https://www.comfydeploy.com/share/comfy-deploy-example-lcm-sdxl',
|
||||
image: {
|
||||
src: '/example-workflows/txt2img-lcm.webp',
|
||||
alt: 'txt2img LCM SDXL',
|
||||
}
|
||||
},
|
||||
{
|
||||
title: "IPAdapter SDXL",
|
||||
description: "Load images and use them as reference for new generations.",
|
||||
previewURL: 'https://www.comfydeploy.com/share/comfy-deploy-example-ip-adapter-sdxl',
|
||||
image: {
|
||||
src: '/example-workflows/ipadapter.webp',
|
||||
alt: 'IPAdapter workflow',
|
||||
}
|
||||
},
|
||||
{
|
||||
title: "Upscale and Add Detail SDXL",
|
||||
description: "Upscale and Add Details to your creations.",
|
||||
previewURL: 'https://www.comfydeploy.com/share/comfy-deploy-example-upscale-and-add-detail-sdxl',
|
||||
image: {
|
||||
src: '/example-workflows/upscale.webp',
|
||||
alt: 'Upscale and Add Detail SDXL',
|
||||
}
|
||||
},
|
||||
{
|
||||
title: "Txt2Img SDXL Turbo",
|
||||
description: "Try SDXL turbo and generate images since 1 step in seconds.",
|
||||
previewURL: 'https://www.comfydeploy.com/share/comfy-deploy-example-txt2img-sdxl-turbo',
|
||||
image: {
|
||||
src: '/example-workflows/txt2img-sdxl-turbo.webp',
|
||||
alt: 'Txt2Img SDXL Turbo',
|
||||
}
|
||||
},
|
||||
{
|
||||
title: "Img2Img SDXL Controlnet",
|
||||
description: "This workflow uses canny. Generate lines of you original image and create variations.",
|
||||
previewURL: 'https://www.comfydeploy.com/share/comfy-deploy-example-img2-img-sdxl-controlnet',
|
||||
image: {
|
||||
src: '/example-workflows/txt2img-controlnet.webp',
|
||||
alt: 'Img2Img SDXL Controlnet',
|
||||
}
|
||||
},
|
||||
{
|
||||
title: "Automatic Inpainting (SEG)",
|
||||
description: "Type what do you want to select and change that area with your prompt.",
|
||||
previewURL: 'https://www.comfydeploy.com/share/comfy-deploy-example-automatic-inpainting-clip-seg',
|
||||
image: {
|
||||
src: '/example-workflows/automatic-inpainting-seg.webp',
|
||||
alt: 'Img2Img SDXL Controlnet',
|
||||
}
|
||||
}
|
||||
];
|
||||
|
||||
|
||||
async function Examples() {
|
||||
return (
|
||||
<div className="w-full py-4">
|
||||
<section className="mx-auto flex max-w-[980px] flex-col items-center gap-2 py-8 md:py-12 md:pb-8 lg:py-24 lg:pb-20">
|
||||
<h1 className="scroll-m-20 text-4xl font-extrabold tracking-tight lg:text-5xl text-center">
|
||||
Check out some examples
|
||||
</h1>
|
||||
<p className="max-w-[560px] text-center text-lg text-muted-foreground">Text to Image, Image to Image, IPAdapter, and more. Here are some examples that you can use to deploy your workflow.</p>
|
||||
</section>
|
||||
<section className="flex justify-center flex-wrap gap-5">
|
||||
{exampleWorkflows.map(workflow => {
|
||||
return <Card className="w-[350px]">
|
||||
<CardHeader>
|
||||
<CardTitle>{workflow.title}</CardTitle>
|
||||
<CardDescription>{workflow.description}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Image src={workflow.image.src} alt={workflow.image.alt} width={350} height={230} />
|
||||
</CardContent>
|
||||
<CardFooter className="flex justify-end gap-2">
|
||||
<Button asChild>
|
||||
<Link href={workflow.previewURL}>View Workflow</Link>
|
||||
</Button>
|
||||
</CardFooter>
|
||||
</Card>;
|
||||
})}
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -29,6 +29,7 @@ export function Navbar() {
|
||||
const { organization } = useOrganization();
|
||||
const _isDesktop = useMediaQuery("(min-width: 1024px)");
|
||||
const [isDesktop, setIsDesktop] = useState(true);
|
||||
const [isSheetOpen, setSheetOpen] = useState(false);
|
||||
useEffect(() => {
|
||||
setIsDesktop(_isDesktop);
|
||||
}, [_isDesktop]);
|
||||
@@ -36,7 +37,7 @@ export function Navbar() {
|
||||
<>
|
||||
<div className="flex flex-row items-center gap-4">
|
||||
{!isDesktop && (
|
||||
<Sheet>
|
||||
<Sheet open={isSheetOpen} onOpenChange={(open) => setSheetOpen(open)}>
|
||||
<SheetTrigger asChild>
|
||||
<button className="flex items-center justify-center w-8 h-8 p-2">
|
||||
<Menu />
|
||||
@@ -47,7 +48,10 @@ export function Navbar() {
|
||||
<SheetTitle className="text-start">Comfy Deploy</SheetTitle>
|
||||
</SheetHeader>
|
||||
<div className="grid h-full grid-rows-[1fr_auto]">
|
||||
<NavbarMenu className=" h-full" />
|
||||
<NavbarMenu
|
||||
className=" h-full"
|
||||
closeSheet={() => setSheetOpen(false)}
|
||||
/>
|
||||
{/* <OrganizationSwitcher
|
||||
appearance={{
|
||||
elements: {
|
||||
|
||||
@@ -5,11 +5,16 @@ import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import { cn } from "@/lib/utils";
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useMediaQuery } from "usehooks-ts";
|
||||
|
||||
export function NavbarMenu({ className }: { className?: string }) {
|
||||
export function NavbarMenu({
|
||||
className,
|
||||
closeSheet,
|
||||
}: {
|
||||
className?: string;
|
||||
closeSheet?: () => void;
|
||||
}) {
|
||||
const _isDesktop = useMediaQuery("(min-width: 1024px)");
|
||||
const [isDesktop, setIsDesktop] = useState(true);
|
||||
useEffect(() => {
|
||||
@@ -19,8 +24,6 @@ export function NavbarMenu({ className }: { className?: string }) {
|
||||
const pathnames = usePathname();
|
||||
const pathname = `/${pathnames.split("/")[1]}`;
|
||||
|
||||
const router = useRouter();
|
||||
|
||||
const pages = [
|
||||
{
|
||||
name: "Workflows",
|
||||
@@ -34,6 +37,10 @@ export function NavbarMenu({ className }: { className?: string }) {
|
||||
name: "API Keys",
|
||||
path: "/api-keys",
|
||||
},
|
||||
{
|
||||
name: "Examples",
|
||||
path: "/examples"
|
||||
}
|
||||
];
|
||||
|
||||
return (
|
||||
@@ -42,18 +49,15 @@ export function NavbarMenu({ className }: { className?: string }) {
|
||||
{isDesktop && (
|
||||
<Tabs
|
||||
defaultValue={pathname}
|
||||
className="w-[300px] flex pointer-events-auto"
|
||||
className="w-fit flex pointer-events-auto"
|
||||
>
|
||||
<TabsList className="grid w-full grid-cols-3">
|
||||
<TabsList className="w-full">
|
||||
{pages.map((page) => (
|
||||
<TabsTrigger
|
||||
key={page.name}
|
||||
value={page.path}
|
||||
onClick={() => {
|
||||
router.push(page.path);
|
||||
}}
|
||||
>
|
||||
{page.name}
|
||||
<Link href={page.path}>{page.name}</Link>
|
||||
</TabsTrigger>
|
||||
))}
|
||||
</TabsList>
|
||||
@@ -68,6 +72,9 @@ export function NavbarMenu({ className }: { className?: string }) {
|
||||
<Link
|
||||
key={page.name}
|
||||
href={page.path}
|
||||
onClick={() => {
|
||||
if (!!closeSheet) closeSheet();
|
||||
}}
|
||||
className="p-2 hover:bg-gray-100/20 hover:underline"
|
||||
>
|
||||
{page.name}
|
||||
|
||||
@@ -5,6 +5,20 @@ export async function OutputRender(props: {
|
||||
run_id: string;
|
||||
filename: string;
|
||||
}) {
|
||||
if (props.filename.endsWith(".mp4") || props.filename.endsWith(".webm")) {
|
||||
const url = await getFileDownloadUrl(
|
||||
`outputs/runs/${props.run_id}/${props.filename}`,
|
||||
);
|
||||
|
||||
return (
|
||||
<video controls autoPlay className="w-[400px]">
|
||||
<source src={url} type="video/mp4" />
|
||||
<source src={url} type="video/webm" />
|
||||
Your browser does not support the video tag.
|
||||
</video>
|
||||
);
|
||||
}
|
||||
|
||||
if (
|
||||
props.filename.endsWith(".png") ||
|
||||
props.filename.endsWith(".gif") ||
|
||||
@@ -12,13 +26,13 @@ export async function OutputRender(props: {
|
||||
props.filename.endsWith(".jpeg")
|
||||
) {
|
||||
const url = await getFileDownloadUrl(
|
||||
`outputs/runs/${props.run_id}/${props.filename}`
|
||||
`outputs/runs/${props.run_id}/${props.filename}`,
|
||||
);
|
||||
|
||||
return <img className="max-w-[200px]" alt={props.filename} src={url} />;
|
||||
} else {
|
||||
const url = await getFileDownloadUrl(
|
||||
`outputs/runs/${props.run_id}/${props.filename}`
|
||||
`outputs/runs/${props.run_id}/${props.filename}`,
|
||||
);
|
||||
// console.log(url);
|
||||
|
||||
|
||||
@@ -124,14 +124,48 @@ export function MachineSelect({
|
||||
);
|
||||
}
|
||||
|
||||
type SelectedMachineStore = {
|
||||
selectedMachine: string | undefined;
|
||||
setSelectedMachine: (machine: string) => void;
|
||||
};
|
||||
|
||||
export const selectedMachineStore = create<SelectedMachineStore>((set) => ({
|
||||
selectedMachine: undefined,
|
||||
setSelectedMachine: (machine) => set(() => ({ selectedMachine: machine })),
|
||||
}));
|
||||
|
||||
export function useSelectedMachine(
|
||||
machines: Awaited<ReturnType<typeof getMachines>>,
|
||||
) {
|
||||
const a = useQueryState("machine", {
|
||||
defaultValue: machines?.[0]?.id ?? "",
|
||||
});
|
||||
): [string, (v: string) => void] {
|
||||
const { selectedMachine, setSelectedMachine } = selectedMachineStore();
|
||||
return [selectedMachine ?? machines?.[0]?.id ?? "", setSelectedMachine];
|
||||
|
||||
return a;
|
||||
// const searchParams = useSearchParams();
|
||||
// const pathname = usePathname();
|
||||
// const router = useRouter();
|
||||
|
||||
// const createQueryString = useCallback(
|
||||
// (name: string, value: string) => {
|
||||
// const params = new URLSearchParams(searchParams.toString());
|
||||
// params.set(name, value);
|
||||
|
||||
// return params.toString();
|
||||
// },
|
||||
// [searchParams],
|
||||
// );
|
||||
|
||||
// return [
|
||||
// searchParams.get("machine") ?? machines?.[0]?.id ?? "",
|
||||
// (v: string) => {
|
||||
// // window.history.pushState(
|
||||
// // "new url",
|
||||
// // "",
|
||||
// // pathname + "?" + createQueryString("machine", v),
|
||||
// // );
|
||||
// // router.push(pathname + "?" + createQueryString("machine", v));
|
||||
// router.replace(pathname + "?" + createQueryString("machine", v));
|
||||
// },
|
||||
// ];
|
||||
}
|
||||
|
||||
type PublicRunStore = {
|
||||
@@ -294,7 +328,7 @@ export function RunWorkflowButton({
|
||||
className="px-1"
|
||||
>
|
||||
<div className="flex justify-end">
|
||||
<AutoFormSubmit>
|
||||
<AutoFormSubmit disabled={isLoading}>
|
||||
Run
|
||||
{isLoading ? <LoadingIcon /> : <Play size={14} />}
|
||||
</AutoFormSubmit>
|
||||
|
||||
@@ -113,7 +113,7 @@ export const registerWorkflowUploadRoute = (app: App) => {
|
||||
workflow_id = _workflow_id;
|
||||
version = _version;
|
||||
} else if (workflow_id) {
|
||||
const workflow = await db
|
||||
const _workflow = await db
|
||||
.select()
|
||||
.from(workflowTable)
|
||||
.where(
|
||||
@@ -126,7 +126,7 @@ export const registerWorkflowUploadRoute = (app: App) => {
|
||||
),
|
||||
);
|
||||
|
||||
if (workflow.length === 0) {
|
||||
if (_workflow.length === 0) {
|
||||
return c.json(
|
||||
{
|
||||
error: "Invalid workflow_id",
|
||||
|
||||
@@ -90,7 +90,12 @@ export const createRun = withServerPromise(
|
||||
Object.entries(workflow_api).forEach(([_, node]) => {
|
||||
if (node.inputs["input_id"] === key) {
|
||||
node.inputs["input_id"] = inputs[key];
|
||||
// Fix for external text default value
|
||||
if (node.class_type == "ComfyUIDeployExternalText") {
|
||||
node.inputs["default_value"] = inputs[key];
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -62,10 +62,10 @@ export async function createDeployments(
|
||||
|
||||
const userName = workflow.org_id
|
||||
? await clerkClient.organizations
|
||||
.getOrganization({
|
||||
organizationId: workflow.org_id,
|
||||
})
|
||||
.then((x) => x.name)
|
||||
.getOrganization({
|
||||
organizationId: workflow.org_id,
|
||||
})
|
||||
.then((x) => x.name)
|
||||
: workflow.user.name;
|
||||
|
||||
await db.insert(deploymentsTable).values({
|
||||
@@ -75,7 +75,8 @@ export async function createDeployments(
|
||||
machine_id,
|
||||
environment,
|
||||
org_id: orgId,
|
||||
share_slug: slugify(`${userName} ${workflow.name}`),
|
||||
// only create share slug if this is public share
|
||||
share_slug: environment == "public-share" ? slugify(`${userName} ${workflow.name}`) : null
|
||||
});
|
||||
}
|
||||
revalidatePath(`/${workflow_id}`);
|
||||
@@ -247,9 +248,9 @@ export async function findUserShareDeployment(share_id: string) {
|
||||
orgId
|
||||
? eq(deploymentsTable.org_id, orgId)
|
||||
: and(
|
||||
eq(deploymentsTable.user_id, userId),
|
||||
isNull(deploymentsTable.org_id),
|
||||
),
|
||||
eq(deploymentsTable.user_id, userId),
|
||||
isNull(deploymentsTable.org_id),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
|
||||
@@ -49,24 +49,26 @@ export async function getRunsData(run_id: string, user?: APIKeyUserType) {
|
||||
for (let i = 0; i < data.outputs.length; i++) {
|
||||
const output = data.outputs[i];
|
||||
|
||||
if (output.data?.images !== undefined) {
|
||||
for (let j = 0; j < output.data?.images.length; j++) {
|
||||
const element = output.data?.images[j];
|
||||
element.url = replaceCDNUrl(
|
||||
`${process.env.SPACES_ENDPOINT}/${process.env.SPACES_BUCKET}/outputs/runs/${data.id}/${element.filename}`
|
||||
);
|
||||
}
|
||||
} else if (output.data?.files !== undefined) {
|
||||
for (let j = 0; j < output.data?.files.length; j++) {
|
||||
const element = output.data?.files[j];
|
||||
element.url = replaceCDNUrl(
|
||||
`${process.env.SPACES_ENDPOINT}/${process.env.SPACES_BUCKET}/outputs/runs/${data.id}/${element.filename}`
|
||||
);
|
||||
}
|
||||
}
|
||||
if (output.data?.images !== undefined)
|
||||
replaceUrls(output.data?.images, data.id);
|
||||
|
||||
if (output.data?.files !== undefined)
|
||||
replaceUrls(output.data?.files, data.id);
|
||||
|
||||
if (output.data?.gifs !== undefined)
|
||||
replaceUrls(output.data?.gifs, data.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
function replaceUrls(dataType: any[], dataId: string) {
|
||||
for (let j = 0; j < dataType.length; j++) {
|
||||
const element = dataType[j];
|
||||
element.url = replaceCDNUrl(
|
||||
`${process.env.SPACES_ENDPOINT}/${process.env.SPACES_BUCKET}/outputs/runs/${dataId}/${element.filename}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||