theanhntp commited on
Commit
5af28ee
·
verified ·
1 Parent(s): 35e5cc0

Upload main.py

Browse files
Files changed (1) hide show
  1. insightface/main.py +296 -0
insightface/main.py ADDED
@@ -0,0 +1,296 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import atexit, requests, subprocess, time, re, os
2
+ from random import randint
3
+ from threading import Timer
4
+ from queue import Queue
5
+ def cloudflared(port, metrics_port, output_queue):
6
+ atexit.register(lambda p: p.terminate(), subprocess.Popen(['/content/cloudflared-linux-amd64', 'tunnel', '--url', f'http://127.0.0.1:{port}', '--metrics', f'127.0.0.1:{metrics_port}'], stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT))
7
+ attempts, tunnel_url = 0, None
8
+ while attempts < 10 and not tunnel_url:
9
+ attempts += 1
10
+ time.sleep(3)
11
+ try:
12
+ tunnel_url = re.search("(?P<url>https?:\/\/[^\s]+.trycloudflare.com)", requests.get(f'http://127.0.0.1:{metrics_port}/metrics').text).group("url")
13
+ except:
14
+ pass
15
+ if not tunnel_url:
16
+ raise Exception("Can't connect to Cloudflare Edge")
17
+ output_queue.put(tunnel_url)
18
+ output_queue, metrics_port = Queue(), randint(8100, 9000)
19
+ thread = Timer(2, cloudflared, args=(8188, metrics_port, output_queue))
20
+ thread.start()
21
+ thread.join()
22
+ tunnel_url = output_queue.get()
23
+ os.environ['webui_url'] = tunnel_url
24
+ print(tunnel_url)
25
+
26
+ import comfy.options
27
+ comfy.options.enable_args_parsing()
28
+
29
+ import subprocess
30
+ import os
31
+ import importlib.util
32
+ import folder_paths
33
+ import time
34
+ from comfy.cli_args import args
35
+
36
+
37
+ def execute_prestartup_script():
38
+ def execute_script(script_path):
39
+ module_name = os.path.splitext(script_path)[0]
40
+ try:
41
+ spec = importlib.util.spec_from_file_location(module_name, script_path)
42
+ module = importlib.util.module_from_spec(spec)
43
+ spec.loader.exec_module(module)
44
+ return True
45
+ except Exception as e:
46
+ print(f"Failed to execute startup-script: {script_path} / {e}")
47
+ return False
48
+
49
+ if args.disable_all_custom_nodes:
50
+ return
51
+
52
+ node_paths = folder_paths.get_folder_paths("custom_nodes")
53
+ for custom_node_path in node_paths:
54
+ possible_modules = os.listdir(custom_node_path)
55
+ node_prestartup_times = []
56
+
57
+ for possible_module in possible_modules:
58
+ module_path = os.path.join(custom_node_path, possible_module)
59
+ if os.path.isfile(module_path) or module_path.endswith(".disabled") or module_path == "__pycache__":
60
+ continue
61
+
62
+ script_path = os.path.join(module_path, "prestartup_script.py")
63
+ if os.path.exists(script_path):
64
+ time_before = time.perf_counter()
65
+ success = execute_script(script_path)
66
+ node_prestartup_times.append((time.perf_counter() - time_before, module_path, success))
67
+ if len(node_prestartup_times) > 0:
68
+ print("\nPrestartup times for custom nodes:")
69
+ for n in sorted(node_prestartup_times):
70
+ if n[2]:
71
+ import_message = ""
72
+ else:
73
+ import_message = " (PRESTARTUP FAILED)"
74
+ print("{:6.1f} seconds{}:".format(n[0], import_message), n[1])
75
+ print()
76
+
77
+ execute_prestartup_script()
78
+
79
+
80
+ # Main code
81
+ import asyncio
82
+ import itertools
83
+ import shutil
84
+ import threading
85
+ import gc
86
+
87
+ import logging
88
+
89
+ if os.name == "nt":
90
+ logging.getLogger("xformers").addFilter(lambda record: 'A matching Triton is not available' not in record.getMessage())
91
+
92
+ if __name__ == "__main__":
93
+ if args.cuda_device is not None:
94
+ os.environ['CUDA_VISIBLE_DEVICES'] = str(args.cuda_device)
95
+ logging.info("Set cuda device to: {}".format(args.cuda_device))
96
+
97
+ if args.deterministic:
98
+ if 'CUBLAS_WORKSPACE_CONFIG' not in os.environ:
99
+ os.environ['CUBLAS_WORKSPACE_CONFIG'] = ":4096:8"
100
+
101
+ import cuda_malloc
102
+
103
+ if args.windows_standalone_build:
104
+ try:
105
+ import fix_torch
106
+ except:
107
+ pass
108
+
109
+ import comfy.utils
110
+ import yaml
111
+
112
+ import execution
113
+ import server
114
+ from server import BinaryEventTypes
115
+ import nodes
116
+ import comfy.model_management
117
+
118
+ def cuda_malloc_warning():
119
+ device = comfy.model_management.get_torch_device()
120
+ device_name = comfy.model_management.get_torch_device_name(device)
121
+ cuda_malloc_warning = False
122
+ if "cudaMallocAsync" in device_name:
123
+ for b in cuda_malloc.blacklist:
124
+ if b in device_name:
125
+ cuda_malloc_warning = True
126
+ if cuda_malloc_warning:
127
+ 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")
128
+
129
+ def prompt_worker(q, server):
130
+ e = execution.PromptExecutor(server)
131
+ last_gc_collect = 0
132
+ need_gc = False
133
+ gc_collect_interval = 10.0
134
+
135
+ while True:
136
+ timeout = 1000.0
137
+ if need_gc:
138
+ timeout = max(gc_collect_interval - (current_time - last_gc_collect), 0.0)
139
+
140
+ queue_item = q.get(timeout=timeout)
141
+ if queue_item is not None:
142
+ item, item_id = queue_item
143
+ execution_start_time = time.perf_counter()
144
+ prompt_id = item[1]
145
+ server.last_prompt_id = prompt_id
146
+
147
+ e.execute(item[2], prompt_id, item[3], item[4])
148
+ need_gc = True
149
+ q.task_done(item_id,
150
+ e.outputs_ui,
151
+ status=execution.PromptQueue.ExecutionStatus(
152
+ status_str='success' if e.success else 'error',
153
+ completed=e.success,
154
+ messages=e.status_messages))
155
+ if server.client_id is not None:
156
+ server.send_sync("executing", { "node": None, "prompt_id": prompt_id }, server.client_id)
157
+
158
+ current_time = time.perf_counter()
159
+ execution_time = current_time - execution_start_time
160
+ logging.info("Prompt executed in {:.2f} seconds".format(execution_time))
161
+
162
+ flags = q.get_flags()
163
+ free_memory = flags.get("free_memory", False)
164
+
165
+ if flags.get("unload_models", free_memory):
166
+ comfy.model_management.unload_all_models()
167
+ need_gc = True
168
+ last_gc_collect = 0
169
+
170
+ if free_memory:
171
+ e.reset()
172
+ need_gc = True
173
+ last_gc_collect = 0
174
+
175
+ if need_gc:
176
+ current_time = time.perf_counter()
177
+ if (current_time - last_gc_collect) > gc_collect_interval:
178
+ comfy.model_management.cleanup_models()
179
+ gc.collect()
180
+ comfy.model_management.soft_empty_cache()
181
+ last_gc_collect = current_time
182
+ need_gc = False
183
+
184
+ async def run(server, address='', port=8188, verbose=True, call_on_start=None):
185
+ await asyncio.gather(server.start(address, port, verbose, call_on_start), server.publish_loop())
186
+
187
+
188
+ def hijack_progress(server):
189
+ def hook(value, total, preview_image):
190
+ comfy.model_management.throw_exception_if_processing_interrupted()
191
+ progress = {"value": value, "max": total, "prompt_id": server.last_prompt_id, "node": server.last_node_id}
192
+
193
+ server.send_sync("progress", progress, server.client_id)
194
+ if preview_image is not None:
195
+ server.send_sync(BinaryEventTypes.UNENCODED_PREVIEW_IMAGE, preview_image, server.client_id)
196
+ comfy.utils.set_progress_bar_global_hook(hook)
197
+
198
+
199
+ def cleanup_temp():
200
+ temp_dir = folder_paths.get_temp_directory()
201
+ if os.path.exists(temp_dir):
202
+ shutil.rmtree(temp_dir, ignore_errors=True)
203
+
204
+
205
+ def load_extra_path_config(yaml_path):
206
+ with open(yaml_path, 'r') as stream:
207
+ config = yaml.safe_load(stream)
208
+ for c in config:
209
+ conf = config[c]
210
+ if conf is None:
211
+ continue
212
+ base_path = None
213
+ if "base_path" in conf:
214
+ base_path = conf.pop("base_path")
215
+ for x in conf:
216
+ for y in conf[x].split("\n"):
217
+ if len(y) == 0:
218
+ continue
219
+ full_path = y
220
+ if base_path is not None:
221
+ full_path = os.path.join(base_path, full_path)
222
+ logging.info("Adding extra search path {} {}".format(x, full_path))
223
+ folder_paths.add_model_folder_path(x, full_path)
224
+
225
+
226
+ if __name__ == "__main__":
227
+ if args.temp_directory:
228
+ temp_dir = os.path.join(os.path.abspath(args.temp_directory), "temp")
229
+ logging.info(f"Setting temp directory to: {temp_dir}")
230
+ folder_paths.set_temp_directory(temp_dir)
231
+ cleanup_temp()
232
+
233
+ if args.windows_standalone_build:
234
+ try:
235
+ import new_updater
236
+ new_updater.update_windows_updater()
237
+ except:
238
+ pass
239
+
240
+ loop = asyncio.new_event_loop()
241
+ asyncio.set_event_loop(loop)
242
+ server = server.PromptServer(loop)
243
+ q = execution.PromptQueue(server)
244
+
245
+ extra_model_paths_config_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "extra_model_paths.yaml")
246
+ if os.path.isfile(extra_model_paths_config_path):
247
+ load_extra_path_config(extra_model_paths_config_path)
248
+
249
+ if args.extra_model_paths_config:
250
+ for config_path in itertools.chain(*args.extra_model_paths_config):
251
+ load_extra_path_config(config_path)
252
+
253
+ nodes.init_extra_nodes(init_custom_nodes=not args.disable_all_custom_nodes)
254
+
255
+ cuda_malloc_warning()
256
+
257
+ server.add_routes()
258
+ hijack_progress(server)
259
+
260
+ threading.Thread(target=prompt_worker, daemon=True, args=(q, server,)).start()
261
+
262
+ if args.output_directory:
263
+ output_dir = os.path.abspath(args.output_directory)
264
+ logging.info(f"Setting output directory to: {output_dir}")
265
+ folder_paths.set_output_directory(output_dir)
266
+
267
+ #These are the default folders that checkpoints, clip and vae models will be saved to when using CheckpointSave, etc.. nodes
268
+ folder_paths.add_model_folder_path("checkpoints", os.path.join(folder_paths.get_output_directory(), "checkpoints"))
269
+ folder_paths.add_model_folder_path("clip", os.path.join(folder_paths.get_output_directory(), "clip"))
270
+ folder_paths.add_model_folder_path("vae", os.path.join(folder_paths.get_output_directory(), "vae"))
271
+
272
+ if args.input_directory:
273
+ input_dir = os.path.abspath(args.input_directory)
274
+ logging.info(f"Setting input directory to: {input_dir}")
275
+ folder_paths.set_input_directory(input_dir)
276
+
277
+ if args.quick_test_for_ci:
278
+ exit(0)
279
+
280
+ call_on_start = None
281
+ if args.auto_launch:
282
+ def startup_server(scheme, address, port):
283
+ import webbrowser
284
+ if os.name == 'nt' and address == '0.0.0.0':
285
+ address = '127.0.0.1'
286
+ webbrowser.open(f"{scheme}://{address}:{port}")
287
+ call_on_start = startup_server
288
+
289
+
290
+ try:
291
+ loop.run_until_complete(run(server, address=args.listen, port=args.port, verbose=not args.dont_print_server, call_on_start=call_on_start))
292
+ subprocess.run(["python", "script.py"])
293
+ except KeyboardInterrupt:
294
+ logging.info("\nStopped server")
295
+
296
+ cleanup_temp()