forked from comfyanonymous/ComfyUI
-
Notifications
You must be signed in to change notification settings - Fork 0
/
start.py
149 lines (115 loc) · 4.63 KB
/
start.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
import os
import sys
import subprocess
import webbrowser
import subprocess
import shutil
from static_file_server import serve_react_app
from aiohttp import web
# These will be installed and imported at runtime
inquirer = None
keyring = None
aiohttp = None
asyncio = None
required_packages = {
'inquirer': 'inquirer',
'keyring': 'keyring',
'aiohttp': 'aiohttp',
'asyncio': 'asyncio'
}
# Attempt to import required packages; install them if necessary
for package, var_name in required_packages.items():
try:
# Try to import the package
globals()[var_name] = __import__(package)
except ImportError:
# If import fails, install the package and try again
subprocess.check_call([sys.executable, "-m", "pip", "install", package])
globals()[var_name] = __import__(package)
PORT=8188 # local Comfy Engine port
OAUTH_PORT=3003 # this port is only used temporarily for oAuth-callback
BASE_DIR = "web"
BUILD_DIR = "web/dist"
SRC_DIR = "web/src"
# Determines if we need to rebuild the project based on the last modified source file date
def is_build_up_to_date():
if not os.path.exists(BUILD_DIR):
return False
src_last_modified = max(os.path.getmtime(root) for root, _, _ in os.walk(SRC_DIR))
build_last_modified = max(os.path.getmtime(root) for root, _, _ in os.walk(BUILD_DIR))
return src_last_modified <= build_last_modified
def find_package_manager():
"""Check for available package managers and return the first one found."""
for manager in ['yarn', 'npm', 'pnpm']:
if shutil.which(manager):
return manager
raise RuntimeError("No suitable JavaScript package manager found. Please install yarn, npm, or pnpm so we can build the client.")
def install_js_dependencies():
manager = find_package_manager()
print(f"Installing dependencies with {manager}...")
subprocess.run([manager, "install"], check=True, cwd='web', shell=True)
def run_js_script(action: str):
manager = find_package_manager()
print(f"{action.capitalize()}ing client with {manager}...")
command = [manager]
if manager in ['npm', 'pnpm']:
command.append("run")
command.append(action)
subprocess.run(command, check=True, cwd=BASE_DIR, shell=True)
async def start_login_callback_server():
event = asyncio.Event()
async def handle_login(request):
query_components = request.rel_url.query
token = query_components.get('token')
if token:
keyring.set_password("void.tech", "user_login_token", token)
print("Token received and stored securely.")
event.set() # Signal that the token has been received
return web.Response(text="Login successful. You can close this window.")
app = web.Application()
app.add_routes([web.get('/', handle_login)])
runner = web.AppRunner(app)
await runner.setup()
site = web.TCPSite(runner, 'localhost', OAUTH_PORT)
await site.start()
print(f"Local server listening on port {OAUTH_PORT}...")
webbrowser.open(f"https://void.tech/login?redirect_uri=http://localhost:{OAUTH_PORT}")
await event.wait() # Wait for the event to be set
await runner.cleanup()
async def get_api_key() -> str:
token = keyring.get_password("void.tech", "user_login_token")
if not token:
print("No token found; please login.")
await start_login_callback_server()
token = keyring.get_password("void.tech", "user_login_token")
return token
async def main():
if not is_build_up_to_date():
install_js_dependencies()
run_js_script('build')
questions = [
inquirer.List('server',
message="Do you want to use a local or remote server?",
choices=['local', 'remote'],
),
]
answers = inquirer.prompt(questions)
if answers['server'] == 'local':
# Start the full Comfy Engine locally
print("Starting local server...")
subprocess.run(["python", "main.py"], check=True)
else:
# Start a simple server to serve the react-app
api_key = await get_api_key()
app = web.Application()
serve_react_app(app, BUILD_DIR, f"https://api.void.tech/{api_key}", 'grpc')
runner = aiohttp.web.AppRunner(app)
await runner.setup()
site = aiohttp.web.TCPSite(runner, 'localhost', PORT)
await site.start()
print(f"Server started at http://localhost:{PORT}")
webbrowser.open(f"http://localhost:{PORT}")
await asyncio.Future() # Keep the server running
pass
if __name__ == "__main__":
asyncio.run(main())