SuperRealCo commited on
Commit
4af304f
·
verified ·
1 Parent(s): e11b5f6

Delete main.py

Browse files
Files changed (1) hide show
  1. main.py +0 -360
main.py DELETED
@@ -1,360 +0,0 @@
1
- import comfy.options
2
- comfy.options.enable_args_parsing()
3
-
4
- import os
5
- import importlib.util
6
- import folder_paths
7
- import time
8
- from comfy.cli_args import args
9
- from app.logger import setup_logger
10
- import itertools
11
- import utils.extra_config
12
- import logging
13
- import sys
14
- from comfy_execution.progress import get_progress_state
15
- from comfy_execution.utils import get_executing_context
16
- from comfy_api import feature_flags
17
-
18
- if __name__ == "__main__":
19
- #NOTE: These do not do anything on core ComfyUI, they are for custom nodes.
20
- os.environ['HF_HUB_DISABLE_TELEMETRY'] = '1'
21
- os.environ['DO_NOT_TRACK'] = '1'
22
-
23
- setup_logger(log_level=args.verbose, use_stdout=args.log_stdout)
24
-
25
- def apply_custom_paths():
26
- # extra model paths
27
- extra_model_paths_config_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "extra_model_paths.yaml")
28
- if os.path.isfile(extra_model_paths_config_path):
29
- utils.extra_config.load_extra_path_config(extra_model_paths_config_path)
30
-
31
- if args.extra_model_paths_config:
32
- for config_path in itertools.chain(*args.extra_model_paths_config):
33
- utils.extra_config.load_extra_path_config(config_path)
34
-
35
- # --output-directory, --input-directory, --user-directory
36
- if args.output_directory:
37
- output_dir = os.path.abspath(args.output_directory)
38
- logging.info(f"Setting output directory to: {output_dir}")
39
- folder_paths.set_output_directory(output_dir)
40
-
41
- # These are the default folders that checkpoints, clip and vae models will be saved to when using CheckpointSave, etc.. nodes
42
- folder_paths.add_model_folder_path("checkpoints", os.path.join(folder_paths.get_output_directory(), "checkpoints"))
43
- folder_paths.add_model_folder_path("clip", os.path.join(folder_paths.get_output_directory(), "clip"))
44
- folder_paths.add_model_folder_path("vae", os.path.join(folder_paths.get_output_directory(), "vae"))
45
- folder_paths.add_model_folder_path("diffusion_models",
46
- os.path.join(folder_paths.get_output_directory(), "diffusion_models"))
47
- folder_paths.add_model_folder_path("loras", os.path.join(folder_paths.get_output_directory(), "loras"))
48
-
49
- if args.input_directory:
50
- input_dir = os.path.abspath(args.input_directory)
51
- logging.info(f"Setting input directory to: {input_dir}")
52
- folder_paths.set_input_directory(input_dir)
53
-
54
- if args.user_directory:
55
- user_dir = os.path.abspath(args.user_directory)
56
- logging.info(f"Setting user directory to: {user_dir}")
57
- folder_paths.set_user_directory(user_dir)
58
-
59
-
60
- def execute_prestartup_script():
61
- if args.disable_all_custom_nodes and len(args.whitelist_custom_nodes) == 0:
62
- return
63
-
64
- def execute_script(script_path):
65
- module_name = os.path.splitext(script_path)[0]
66
- try:
67
- spec = importlib.util.spec_from_file_location(module_name, script_path)
68
- module = importlib.util.module_from_spec(spec)
69
- spec.loader.exec_module(module)
70
- return True
71
- except Exception as e:
72
- logging.error(f"Failed to execute startup-script: {script_path} / {e}")
73
- return False
74
-
75
- node_paths = folder_paths.get_folder_paths("custom_nodes")
76
- for custom_node_path in node_paths:
77
- possible_modules = os.listdir(custom_node_path)
78
- node_prestartup_times = []
79
-
80
- for possible_module in possible_modules:
81
- module_path = os.path.join(custom_node_path, possible_module)
82
- if os.path.isfile(module_path) or module_path.endswith(".disabled") or module_path == "__pycache__":
83
- continue
84
-
85
- script_path = os.path.join(module_path, "prestartup_script.py")
86
- if os.path.exists(script_path):
87
- if args.disable_all_custom_nodes and possible_module not in args.whitelist_custom_nodes:
88
- logging.info(f"Prestartup Skipping {possible_module} due to disable_all_custom_nodes and whitelist_custom_nodes")
89
- continue
90
- time_before = time.perf_counter()
91
- success = execute_script(script_path)
92
- node_prestartup_times.append((time.perf_counter() - time_before, module_path, success))
93
- if len(node_prestartup_times) > 0:
94
- logging.info("\nPrestartup times for custom nodes:")
95
- for n in sorted(node_prestartup_times):
96
- if n[2]:
97
- import_message = ""
98
- else:
99
- import_message = " (PRESTARTUP FAILED)"
100
- logging.info("{:6.1f} seconds{}: {}".format(n[0], import_message, n[1]))
101
- logging.info("")
102
-
103
- apply_custom_paths()
104
- execute_prestartup_script()
105
-
106
-
107
- # Main code
108
- import asyncio
109
- import shutil
110
- import threading
111
- import gc
112
-
113
-
114
- if os.name == "nt":
115
- logging.getLogger("xformers").addFilter(lambda record: 'A matching Triton is not available' not in record.getMessage())
116
-
117
- if __name__ == "__main__":
118
- if args.cuda_device is not None:
119
- os.environ['CUDA_VISIBLE_DEVICES'] = str(args.cuda_device)
120
- os.environ['HIP_VISIBLE_DEVICES'] = str(args.cuda_device)
121
- logging.info("Set cuda device to: {}".format(args.cuda_device))
122
-
123
- if args.oneapi_device_selector is not None:
124
- os.environ['ONEAPI_DEVICE_SELECTOR'] = args.oneapi_device_selector
125
- logging.info("Set oneapi device selector to: {}".format(args.oneapi_device_selector))
126
-
127
- if args.deterministic:
128
- if 'CUBLAS_WORKSPACE_CONFIG' not in os.environ:
129
- os.environ['CUBLAS_WORKSPACE_CONFIG'] = ":4096:8"
130
-
131
- import cuda_malloc
132
-
133
- if 'torch' in sys.modules:
134
- logging.warning("WARNING: Potential Error in code: Torch already imported, torch should never be imported before this point.")
135
-
136
- import comfy.utils
137
-
138
- import execution
139
- import server
140
- from protocol import BinaryEventTypes
141
- import nodes
142
- import comfy.model_management
143
- import comfyui_version
144
- import app.logger
145
- import hook_breaker_ac10a0
146
-
147
- def cuda_malloc_warning():
148
- device = comfy.model_management.get_torch_device()
149
- device_name = comfy.model_management.get_torch_device_name(device)
150
- cuda_malloc_warning = False
151
- if "cudaMallocAsync" in device_name:
152
- for b in cuda_malloc.blacklist:
153
- if b in device_name:
154
- cuda_malloc_warning = True
155
- if cuda_malloc_warning:
156
- logging.warning("\nWARNING: this card most likely does not support cuda-malloc, if you get \"CUDA error\" please run ComfyUI with: --disable-cuda-malloc\n")
157
-
158
-
159
- def prompt_worker(q, server_instance):
160
- current_time: float = 0.0
161
- cache_type = execution.CacheType.CLASSIC
162
- if args.cache_lru > 0:
163
- cache_type = execution.CacheType.LRU
164
- elif args.cache_none:
165
- cache_type = execution.CacheType.DEPENDENCY_AWARE
166
-
167
- e = execution.PromptExecutor(server_instance, cache_type=cache_type, cache_size=args.cache_lru)
168
- last_gc_collect = 0
169
- need_gc = False
170
- gc_collect_interval = 10.0
171
-
172
- while True:
173
- timeout = 1000.0
174
- if need_gc:
175
- timeout = max(gc_collect_interval - (current_time - last_gc_collect), 0.0)
176
-
177
- queue_item = q.get(timeout=timeout)
178
- if queue_item is not None:
179
- item, item_id = queue_item
180
- execution_start_time = time.perf_counter()
181
- prompt_id = item[1]
182
- server_instance.last_prompt_id = prompt_id
183
-
184
- e.execute(item[2], prompt_id, item[3], item[4])
185
- need_gc = True
186
- q.task_done(item_id,
187
- e.history_result,
188
- status=execution.PromptQueue.ExecutionStatus(
189
- status_str='success' if e.success else 'error',
190
- completed=e.success,
191
- messages=e.status_messages))
192
- if server_instance.client_id is not None:
193
- server_instance.send_sync("executing", {"node": None, "prompt_id": prompt_id}, server_instance.client_id)
194
-
195
- current_time = time.perf_counter()
196
- execution_time = current_time - execution_start_time
197
-
198
- # Log Time in a more readable way after 10 minutes
199
- if execution_time > 600:
200
- execution_time = time.strftime("%H:%M:%S", time.gmtime(execution_time))
201
- logging.info(f"Prompt executed in {execution_time}")
202
- else:
203
- logging.info("Prompt executed in {:.2f} seconds".format(execution_time))
204
-
205
- flags = q.get_flags()
206
- free_memory = flags.get("free_memory", False)
207
-
208
- if flags.get("unload_models", free_memory):
209
- comfy.model_management.unload_all_models()
210
- need_gc = True
211
- last_gc_collect = 0
212
-
213
- if free_memory:
214
- e.reset()
215
- need_gc = True
216
- last_gc_collect = 0
217
-
218
- if need_gc:
219
- current_time = time.perf_counter()
220
- if (current_time - last_gc_collect) > gc_collect_interval:
221
- gc.collect()
222
- comfy.model_management.soft_empty_cache()
223
- last_gc_collect = current_time
224
- need_gc = False
225
- hook_breaker_ac10a0.restore_functions()
226
-
227
-
228
- async def run(server_instance, address='', port=8188, verbose=True, call_on_start=None):
229
- addresses = []
230
- for addr in address.split(","):
231
- addresses.append((addr, port))
232
- await asyncio.gather(
233
- server_instance.start_multi_address(addresses, call_on_start, verbose), server_instance.publish_loop()
234
- )
235
-
236
- def hijack_progress(server_instance):
237
- def hook(value, total, preview_image, prompt_id=None, node_id=None):
238
- executing_context = get_executing_context()
239
- if prompt_id is None and executing_context is not None:
240
- prompt_id = executing_context.prompt_id
241
- if node_id is None and executing_context is not None:
242
- node_id = executing_context.node_id
243
- comfy.model_management.throw_exception_if_processing_interrupted()
244
- if prompt_id is None:
245
- prompt_id = server_instance.last_prompt_id
246
- if node_id is None:
247
- node_id = server_instance.last_node_id
248
- progress = {"value": value, "max": total, "prompt_id": prompt_id, "node": node_id}
249
- get_progress_state().update_progress(node_id, value, total, preview_image)
250
-
251
- server_instance.send_sync("progress", progress, server_instance.client_id)
252
- if preview_image is not None:
253
- # Only send old method if client doesn't support preview metadata
254
- if not feature_flags.supports_feature(
255
- server_instance.sockets_metadata,
256
- server_instance.client_id,
257
- "supports_preview_metadata",
258
- ):
259
- server_instance.send_sync(
260
- BinaryEventTypes.UNENCODED_PREVIEW_IMAGE,
261
- preview_image,
262
- server_instance.client_id,
263
- )
264
-
265
- comfy.utils.set_progress_bar_global_hook(hook)
266
-
267
-
268
- def cleanup_temp():
269
- temp_dir = folder_paths.get_temp_directory()
270
- if os.path.exists(temp_dir):
271
- shutil.rmtree(temp_dir, ignore_errors=True)
272
-
273
-
274
- def setup_database():
275
- try:
276
- from app.database.db import init_db, dependencies_available
277
- if dependencies_available():
278
- init_db()
279
- except Exception as e:
280
- logging.error(f"Failed to initialize database. Please ensure you have installed the latest requirements. If the error persists, please report this as in future the database will be required: {e}")
281
-
282
-
283
- def start_comfyui(asyncio_loop=None):
284
- """
285
- Starts the ComfyUI server using the provided asyncio event loop or creates a new one.
286
- Returns the event loop, server instance, and a function to start the server asynchronously.
287
- """
288
- if args.temp_directory:
289
- temp_dir = os.path.join(os.path.abspath(args.temp_directory), "temp")
290
- logging.info(f"Setting temp directory to: {temp_dir}")
291
- folder_paths.set_temp_directory(temp_dir)
292
- cleanup_temp()
293
-
294
- if args.windows_standalone_build:
295
- try:
296
- import new_updater
297
- new_updater.update_windows_updater()
298
- except:
299
- pass
300
-
301
- if not asyncio_loop:
302
- asyncio_loop = asyncio.new_event_loop()
303
- asyncio.set_event_loop(asyncio_loop)
304
- prompt_server = server.PromptServer(asyncio_loop)
305
-
306
- hook_breaker_ac10a0.save_functions()
307
- nodes.init_extra_nodes(
308
- init_custom_nodes=(not args.disable_all_custom_nodes) or len(args.whitelist_custom_nodes) > 0,
309
- init_api_nodes=not args.disable_api_nodes
310
- )
311
- hook_breaker_ac10a0.restore_functions()
312
-
313
- cuda_malloc_warning()
314
- setup_database()
315
-
316
- prompt_server.add_routes()
317
- hijack_progress(prompt_server)
318
-
319
- threading.Thread(target=prompt_worker, daemon=True, args=(prompt_server.prompt_queue, prompt_server,)).start()
320
-
321
- if args.quick_test_for_ci:
322
- exit(0)
323
-
324
- os.makedirs(folder_paths.get_temp_directory(), exist_ok=True)
325
- call_on_start = None
326
- if args.auto_launch:
327
- def startup_server(scheme, address, port):
328
- import webbrowser
329
- if os.name == 'nt' and address == '0.0.0.0':
330
- address = '127.0.0.1'
331
- if ':' in address:
332
- address = "[{}]".format(address)
333
- webbrowser.open(f"{scheme}://{address}:{port}")
334
- call_on_start = startup_server
335
-
336
- async def start_all():
337
- await prompt_server.setup()
338
- await run(prompt_server, address=args.listen, port=args.port, verbose=not args.dont_print_server, call_on_start=call_on_start)
339
-
340
- # Returning these so that other code can integrate with the ComfyUI loop and server
341
- return asyncio_loop, prompt_server, start_all
342
-
343
-
344
- if __name__ == "__main__":
345
- # Running directly, just start ComfyUI.
346
- logging.info("Python version: {}".format(sys.version))
347
- logging.info("ComfyUI version: {}".format(comfyui_version.__version__))
348
-
349
- if sys.version_info.major == 3 and sys.version_info.minor < 10:
350
- logging.warning("WARNING: You are using a python version older than 3.10, please upgrade to a newer one. 3.12 and above is recommended.")
351
-
352
- event_loop, _, start_all_func = start_comfyui()
353
- try:
354
- x = start_all_func()
355
- app.logger.print_startup_warnings()
356
- event_loop.run_until_complete(x)
357
- except KeyboardInterrupt:
358
- logging.info("\nStopped server")
359
-
360
- cleanup_temp()