Repository navigation
Expand file tree
/
Copy pathserver.py
More file actions
4732 lines (4283 loc) · 228 KB
/
Copy pathserver.py
File metadata and controls
4732 lines (4283 loc) · 228 KB
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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
ComfyAgent — 可视化创作控制台后端
纯 Python 标准库实现,零第三方依赖。
功能:ComfyUI 代理/进度转发(SSE)、成果画廊(扫描 output 目录 + PNG 元数据 + 视频缩略图)、
工作流库 + UI->API 转换、Obsidian 归档、规则式 Agent。
"""
import base64
import hashlib
import json
import mimetypes
import os
import queue as queue_mod
import random
import re
import shlex
import shutil
import socket
import struct
import subprocess
import sys
import threading
import tempfile
import time
import traceback
import urllib.error
import urllib.parse
import urllib.request
import uuid
import webbrowser
from datetime import datetime
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
# 打包成 exe(PyInstaller)时:静态资源在 _MEIPASS,数据目录放系统 APPDATA(重建/更新永不触碰用户数据)
if getattr(sys, "frozen", False):
BASE_DIR = os.path.dirname(sys.executable)
STATIC_DIR = os.path.join(sys._MEIPASS, "static")
DATA_DIR = os.path.join(os.environ.get("APPDATA") or os.path.expanduser("~/AppData/Roaming"), "ComfyAgent", "data")
else:
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_DIR = os.path.join(BASE_DIR, "static")
DATA_DIR = os.path.join(BASE_DIR, "data")
WORKFLOW_DIR = os.path.join(DATA_DIR, "workflows")
CACHE_DIR = os.path.join(DATA_DIR, "cache")
THUMB_DIR = os.path.join(CACHE_DIR, "thumbs")
TRASH_DIR = os.path.join(DATA_DIR, "trash")
SETTINGS_FILE = os.path.join(DATA_DIR, "settings.json")
RUNS_FILE = os.path.join(DATA_DIR, "runs.json")
ARCHIVE_LOG = os.path.join(DATA_DIR, "archives.json")
DEFAULT_SETTINGS = {
"port": 8190,
"comfy_url": "http://127.0.0.1:8188",
"output_dir": r"D:\tools\ComfyUI-aki-v3\ComfyUI\output",
"vault_path": r"E:\work\obsidian\TungwaiKu",
"zhipu_key": "",
"zhipu_model": "glm-4-flash",
"client_id": uuid.uuid4().hex,
"gallery_cap": 2000,
"comfy_dir": r"D:\tools\ComfyUI-aki-v3\ComfyUI",
"comfy_python": r"D:\tools\ComfyUI-aki-v3\python\python.exe",
"comfy_launch_args": "--listen 127.0.0.1 --port 8188 --reserve-vram 2.5 --vram-headroom 0.5 --disable-pinned-memory",
"gitee_repo": "IvenKooLab/comfy-agent",
"gitee_token": "",
"llm_provider": "zhipu",
"llm_base_url": "https://open.bigmodel.cn/api/paas/v4",
"llm_key": "",
"llm_model": "glm-4-flash",
"comfy_watchdog": False, # 默认关闭:避免用户手动停 ComfyUI(如打游戏)时被自动拉起抢 GPU
"comfy_autorequeue": True,
"batch_auto_retry": 2,
"lan_access": False,
}
# LLM 厂商预设(OpenAI 兼容协议);models 为兜底列表,优先用 /models 动态拉取
LLM_PRESETS = {
"zhipu": {"name": "智谱 GLM", "base": "https://open.bigmodel.cn/api/paas/v4", "models": ["glm-4-flash", "glm-4-plus", "glm-4.5", "glm-4.5-air"]},
"deepseek": {"name": "DeepSeek", "base": "https://api.deepseek.com/v1", "models": ["deepseek-chat", "deepseek-reasoner"]},
"moonshot": {"name": "月之暗面 Kimi", "base": "https://api.moonshot.cn/v1", "models": ["moonshot-v1-8k", "moonshot-v1-32k", "kimi-k2-0711-preview"]},
"dashscope": {"name": "阿里通义千问", "base": "https://dashscope.aliyuncs.com/compatible-mode/v1", "models": ["qwen-plus", "qwen-turbo", "qwen-max"]},
"siliconflow": {"name": "硅基流动", "base": "https://api.siliconflow.cn/v1", "models": ["Qwen/Qwen2.5-7B-Instruct", "deepseek-ai/DeepSeek-V3"]},
"openai": {"name": "OpenAI", "base": "https://api.openai.com/v1", "models": ["gpt-4o-mini", "gpt-4o"]},
"custom": {"name": "自定义 OpenAI 兼容", "base": "", "models": []},
}
MEDIA_EXTS = {".png", ".jpg", ".jpeg", ".webp", ".gif", ".bmp"}
VIDEO_EXTS = {".mp4", ".webm", ".mov", ".mkv", ".avi"}
FFMPEG = shutil.which("ffmpeg")
# ---------------------------------------------------------------- utilities
def ensure_dirs():
for d in (DATA_DIR, WORKFLOW_DIR, CACHE_DIR, THUMB_DIR, os.path.dirname(SETTINGS_FILE)):
os.makedirs(d, exist_ok=True)
os.makedirs(THUMB_DIR, exist_ok=True)
def load_settings():
s = dict(DEFAULT_SETTINGS)
if os.path.exists(SETTINGS_FILE):
try:
with open(SETTINGS_FILE, encoding="utf-8") as f:
s.update(json.load(f))
except Exception:
pass
# 旧版 zhipu_key/zhipu_model → 新 llm_* 字段迁移
if not s.get("llm_key") and s.get("zhipu_key"):
s["llm_provider"] = "zhipu"
s["llm_key"] = s["zhipu_key"]
s["llm_model"] = s.get("zhipu_model", "glm-4-flash")
s["llm_base_url"] = LLM_PRESETS["zhipu"]["base"]
return s
def write_text_atomic(path, text):
"""原子写文本:先写 .tmp 再 os.replace,断电/崩溃不会留下半截文件。"""
d = os.path.dirname(path)
if d:
os.makedirs(d, exist_ok=True)
fd, tmp = tempfile.mkstemp(prefix=".comfy-", suffix=".tmp", dir=d or ".")
try:
with os.fdopen(fd, "w", encoding="utf-8") as f:
f.write(text)
os.replace(tmp, path)
finally:
if os.path.exists(tmp):
os.remove(tmp)
def save_settings(s):
write_text_atomic(SETTINGS_FILE, json.dumps(s, ensure_ascii=False, indent=2))
def backup_now(reason="manual"):
"""打包核心数据(工作流库/批次/角色/设置/任务记录)到 data/backups,保留最近 20 份。"""
import zipfile
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
bdir = os.path.join(DATA_DIR, "backups")
os.makedirs(bdir, exist_ok=True)
dst = os.path.join(bdir, f"backup_{ts}_{reason}.zip")
with zipfile.ZipFile(dst, "w", zipfile.ZIP_DEFLATED) as z:
for sub in ("workflows", "batches", "characters"):
root = os.path.join(DATA_DIR, sub)
if os.path.isdir(root):
for dp, _, fs in os.walk(root):
for f in fs:
fp = os.path.join(dp, f)
z.write(fp, os.path.relpath(fp, DATA_DIR))
for f in (SETTINGS_FILE, RUNS_FILE, ARCHIVE_LOG):
if os.path.isfile(f):
z.write(f, os.path.relpath(f, DATA_DIR))
zips = sorted([os.path.join(bdir, f) for f in os.listdir(bdir) if f.startswith("backup_")],
key=os.path.getmtime)
for old in zips[:-20]:
try:
os.remove(old)
except OSError:
pass
return {"file": os.path.basename(dst), "count": len(zips[-20:])}
SETTINGS = None # set in main()
def read_json_file(path, default):
try:
with open(path, encoding="utf-8") as f:
return json.load(f)
except Exception:
return default
def write_json_file(path, obj):
write_text_atomic(path, json.dumps(obj, ensure_ascii=False, indent=2))
def human_size(n):
for unit in ("B", "KB", "MB", "GB", "TB"):
if n < 1024 or unit == "TB":
return f"{n:.1f}{unit}" if unit != "B" else f"{n}B"
n /= 1024.0
def kind_of(ext):
return "video" if ext in VIDEO_EXTS else "image"
def safe_name(name):
return re.sub(r'[\\/:*?"<>|]', "_", name).strip()[:80]
# ---------------------------------------------------------------- ComfyUI client
class ComfyClient:
"""HTTP 客户端 + 便携 WebSocket 客户端(标准库实现)。"""
def __init__(self, base_url):
self.base = base_url.rstrip("/")
self.online = False
self.object_info_cache = None
self.object_info_ts = 0
def http(self, path, payload=None, method=None, timeout=10):
url = self.base + path
data = json.dumps(payload).encode() if payload is not None else None
req = urllib.request.Request(url, data=data, method=method or ("POST" if data else "GET"))
req.add_header("Content-Type", "application/json")
with urllib.request.urlopen(req, timeout=timeout) as r:
body = r.read()
try:
return json.loads(body)
except Exception:
return body
def probe(self):
try:
st = self.http("/system_stats", timeout=4)
self.online = True
return st
except Exception:
self.online = False
return None
def object_info(self, max_age=600):
if self.object_info_cache and time.time() - self.object_info_ts < max_age:
return self.object_info_cache
oi = self.http("/object_info", timeout=60)
self.object_info_cache = oi
self.object_info_ts = time.time()
return oi
class MiniWS:
"""够用的 WebSocket 客户端:握手 + 文本帧收发 + ping/pong。"""
def __init__(self, url):
self.url = url
self.sock = None
self.alive = False
def connect(self):
u = urllib.parse.urlparse(self.url)
host, port = u.hostname, u.port or (443 if u.scheme == "wss" else 80)
path = u.path + ("?" + u.query if u.query else "")
key = base64.b64encode(os.urandom(16)).decode()
self.sock = socket.create_connection((host, port), timeout=10)
self.sock.settimeout(None)
req = (f"GET {path} HTTP/1.1\r\nHost: {host}:{port}\r\nUpgrade: websocket\r\n"
f"Connection: Upgrade\r\nSec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n")
self.sock.sendall(req.encode())
buf = b""
while b"\r\n\r\n" not in buf:
chunk = self.sock.recv(4096)
if not chunk:
raise ConnectionError("ws handshake eof")
buf += chunk
head, _, rest = buf.partition(b"\r\n\r\n")
if b"101" not in head.split(b"\r\n")[0]:
raise ConnectionError("ws handshake rejected: " + head[:120].decode("utf-8", "ignore"))
self.alive = True
self._leftover = rest
def _read_exact(self, n):
data = self._leftover
self._leftover = b""
while len(data) < n:
chunk = self.sock.recv(65536)
if not chunk:
raise ConnectionError("ws eof")
data += chunk
self._leftover = data[n:]
return data[:n]
def recv_text(self):
"""阻塞收一帧;返回 (opcode, text-or-None)。二进制帧直接丢弃。"""
while True:
hdr = self._read_exact(2)
fin_op = hdr[0]
opcode = fin_op & 0x0F
mask_len = hdr[1]
masked = bool(mask_len & 0x80)
length = mask_len & 0x7F
if length == 126:
length = struct.unpack(">H", self._read_exact(2))[0]
elif length == 127:
length = struct.unpack(">Q", self._read_exact(8))[0]
mask = self._read_exact(4) if masked else None
payload = self._read_exact(length) if length else b""
if opcode == 0x9: # ping -> pong
self._send_frame(0xA, payload)
continue
if opcode == 0x8: # close
raise ConnectionError("ws closed by server")
if opcode in (0x1, 0x2):
return opcode, payload.decode("utf-8", "replace")
# pong / 其他:忽略
def _send_frame(self, opcode, payload=b""):
mask = os.urandom(4)
header = bytes([0x80 | opcode])
n = len(payload)
if n < 126:
header += bytes([0x80 | n])
elif n < 65536:
header += bytes([0x80 | 126]) + struct.pack(">H", n)
else:
header += bytes([0x80 | 127]) + struct.pack(">Q", n)
masked = bytes(b ^ mask[i % 4] for i, b in enumerate(payload))
self.sock.sendall(header + mask + masked)
def close(self):
self.alive = False
try:
if self.sock:
self._send_frame(0x8)
except Exception:
pass
finally:
if self.sock:
self.sock.close()
COMFY = None # set in main()
# ---------------------------------------------------------------- SSE hub
class SSEHub:
def __init__(self):
self.lock = threading.Lock()
self.subscribers = []
self.state = {"comfy_online": False, "queue_remaining": 0, "progress": None,
"executing": None, "last_event": None}
def subscribe(self):
q = queue_mod.Queue(maxsize=500)
with self.lock:
self.subscribers.append(q)
return q
def unsubscribe(self, q):
with self.lock:
if q in self.subscribers:
self.subscribers.remove(q)
def publish(self, event):
self.state["last_event"] = event
if event.get("type") == "status":
self.state["queue_remaining"] = event.get("data", {}).get("value", self.state["queue_remaining"])
elif event.get("type") == "progress":
d = event.get("data", {})
self.state["progress"] = {"value": d.get("value"), "max": d.get("max"),
"prompt_id": d.get("prompt_id"), "node": d.get("node")}
elif event.get("type") == "executing":
d = event.get("data", {})
if d.get("node") is None:
self.state["progress"] = None
self.state["executing"] = None
else:
self.state["executing"] = d
elif event.get("type") in ("execution_success", "execution_error", "execution_interrupted"):
self.state["progress"] = None
self.state["executing"] = None
with self.lock:
subs = list(self.subscribers)
for q in subs:
try:
q.put_nowait(event)
except queue_mod.Full:
pass
HUB = SSEHub()
def ws_monitor_loop():
"""维持与 ComfyUI 的 WS 长连,事件转发到 SSE hub。"""
while True:
client = COMFY
ws_url = client.base.replace("http://", "ws://").replace("https://", "wss://")
ws_url += "/ws?clientId=" + SETTINGS["client_id"]
ws = MiniWS(ws_url)
try:
ws.connect()
client.online = True
HUB.state["comfy_online"] = True
HUB.publish({"type": "comfy_status", "data": {"online": True}})
def close_on_change(ws=ws, client=client):
while ws.alive and COMFY is client:
time.sleep(0.2)
if ws.alive and ws.sock:
try:
ws.sock.shutdown(socket.SHUT_RDWR)
except OSError:
pass
threading.Thread(target=close_on_change, daemon=True).start()
while True:
if COMFY is not client:
break
opcode, text = ws.recv_text()
if opcode != 1:
continue
try:
msg = json.loads(text)
except Exception:
continue
if isinstance(msg, dict) and "type" in msg:
HUB.publish(msg)
except Exception:
pass
finally:
ws.close()
client.online = False
HUB.state["comfy_online"] = False
HUB.state["progress"] = None
HUB.state["executing"] = None
HUB.publish({"type": "comfy_status", "data": {"online": False}})
time.sleep(4)
def queue_poll_loop():
"""WS 断开时的兜底:轮询 /queue。"""
last = None
while True:
time.sleep(3)
if COMFY.online:
continue
try:
q = COMFY.http("/queue", timeout=4)
running, pending = len(q.get("queue_running", [])), len(q.get("queue_pending", []))
cur = (running, pending)
if cur != last:
last = cur
HUB.publish({"type": "queue_state", "data": {"running": running, "pending": pending}})
except Exception:
pass
# ---------------------------------------------------------------- gallery
_gallery_cache = {"ts": 0, "items": []}
_meta_cache = {}
def scan_gallery(force=False):
if not force and time.time() - _gallery_cache["ts"] < 4:
return _gallery_cache["items"]
root = SETTINGS["output_dir"]
items = []
if os.path.isdir(root):
for dirpath, dirnames, filenames in os.walk(root):
dirnames[:] = [d for d in dirnames if not d.startswith(".")]
for fn in filenames:
ext = os.path.splitext(fn)[1].lower()
if ext not in MEDIA_EXTS and ext not in VIDEO_EXTS:
continue
full = os.path.join(dirpath, fn)
try:
st = os.stat(full)
except OSError:
continue
rel = os.path.relpath(full, root).replace("\\", "/")
it = {"path": rel, "name": fn, "kind": kind_of(ext), "ext": ext,
"size": st.st_size, "mtime": int(st.st_mtime)}
if ext == ".png":
try:
w, h = png_size(full)
it["w"], it["h"] = w, h
except Exception:
pass
items.append(it)
items.sort(key=lambda x: x["mtime"], reverse=True)
items = items[:SETTINGS.get("gallery_cap", 2000)]
_gallery_cache["ts"] = time.time()
_gallery_cache["items"] = items
return items
def png_size(path):
with open(path, "rb") as f:
head = f.read(26)
if head[:8] != b"\x89PNG\r\n\x1a\n" or head[12:16] != b"IHDR":
return None, None
w, h = struct.unpack(">II", head[16:24])
return w, h
def png_workflow_meta(path):
"""读取 ComfyUI 写入 PNG tEXt 块里的 prompt(API) 与 workflow(UI) 元数据。"""
key = (path, os.path.getmtime(path) if os.path.exists(path) else 0)
if key in _meta_cache:
return _meta_cache[key]
out = {"prompt": None, "workflow": None}
try:
with open(path, "rb") as f:
data = f.read()
pos = 8
while pos + 8 <= len(data):
(length,) = struct.unpack(">I", data[pos:pos + 4])
ctype = data[pos + 4:pos + 8]
cdata = data[pos + 8:pos + 8 + length]
if ctype == b"tEXt":
null = cdata.find(b"\x00")
if null > 0:
kw = cdata[:null].decode("latin-1")
val = cdata[null + 1:].decode("utf-8", "replace")
if kw in ("prompt", "workflow"):
try:
out[kw] = json.loads(val)
except Exception:
pass
elif ctype == b"IDAT":
break
pos += 12 + length
except Exception:
pass
_meta_cache[key] = out
return out
def summarize_api_graph(api):
"""把 API 工作流摘要成可读参数(画廊详情/归档用)。"""
if not isinstance(api, dict):
return {}
summary = {"model": None, "sampler": None, "steps": None, "cfg": None, "seed": None,
"dimensions": None, "prompt": None, "negative": None, "nodes": len(api)}
for nid, node in api.items():
ct = node.get("class_type", "")
ins = node.get("inputs", {}) or {}
if ct in ("CheckpointLoaderSimple", "CheckpointLoader", "UNETLoader", "VAELoader"):
for k in ("ckpt_name", "unet_name", "vae_name"):
if isinstance(ins.get(k), str):
summary["model"] = ins[k]
elif "KSampler" in ct or "Sampler" in ct and "Custom" not in ct:
for k in ("steps", "cfg", "seed", "sampler_name", "denoise"):
v = ins.get(k)
if isinstance(v, (int, float, str)):
summary[{"sampler_name": "sampler"}.get(k, k)] = v
elif ct == "EmptySD3LatentImage" or ct == "EmptyLatentImage":
summary["dimensions"] = f"{ins.get('width')}x{ins.get('height')}"
elif ct == "CLIPTextEncode":
t = ins.get("text")
if isinstance(t, str):
if summary["prompt"] is None:
summary["prompt"] = t
elif summary["negative"] is None:
summary["negative"] = t
for k, v in list(summary.items()):
if isinstance(v, str) and len(v) > 500:
summary[k] = v[:500] + "…"
return summary
def thumb_path_for(rel, mtime):
h = hashlib.md5(f"{rel}|{mtime}".encode()).hexdigest()[:16]
return os.path.join(THUMB_DIR, h + ".jpg")
def make_video_thumb(src, dst):
if not FFMPEG:
return False
try:
r = subprocess.run([FFMPEG, "-v", "error", "-ss", "0.5", "-i", src,
"-frames:v", "1", "-vf", "scale=480:-2", "-q:v", "4", "-y", dst],
capture_output=True, timeout=60, creationflags=0x08000000)
return r.returncode == 0 and os.path.exists(dst)
except Exception:
return False
def make_image_thumb(src, dst):
if not FFMPEG:
return False
try:
r = subprocess.run([FFMPEG, "-v", "error", "-i", src, "-vf", "scale='min(720,iw)':-2",
"-q:v", "4", "-y", dst],
capture_output=True, timeout=60, creationflags=0x08000000)
return r.returncode == 0 and os.path.exists(dst)
except Exception:
return False
def path_within(root, rel):
"""Resolve symlinks and require a complete directory boundary."""
root = os.path.realpath(root)
full = os.path.realpath(os.path.join(root, rel))
try:
return full if os.path.commonpath([root, full]) == root else None
except ValueError:
return None
def resolve_media(rel):
"""解析画廊相对路径。SETTINGS 未初始化(模块被单独导入/测试)时安全返回 None。"""
root = (SETTINGS or {}).get("output_dir") if isinstance(SETTINGS, dict) else None
if not root or not rel:
return None
return path_within(root, rel)
# ---------------------------------------------------------------- workflows store
BUILTIN_WORKFLOWS = {
"Flux 文生图(内置)": {
"id": "builtin-flux",
"name": "Flux 文生图(内置)",
"builtin": True,
"updated": "2026-08-29 10:00",
"api": {
"1": {"class_type": "CheckpointLoaderSimple", "inputs": {"ckpt_name": "flux1-dev-fp8.safetensors"}},
"2": {"class_type": "CLIPTextEncode", "inputs": {"clip": ["1", 1], "text": "masterpiece, best quality"}},
"3": {"class_type": "FluxGuidance", "inputs": {"conditioning": ["2", 0], "guidance": 3.5}},
"4": {"class_type": "EmptySD3LatentImage", "inputs": {"width": 832, "height": 1216, "batch_size": 1}},
"5": {"class_type": "KSampler", "inputs": {"model": ["1", 0], "positive": ["3", 0], "negative": ["3", 0],
"seed": 0, "steps": 20, "cfg": 1.0, "sampler_name": "euler",
"scheduler": "simple", "denoise": 1.0, "latent_image": ["4", 0]}},
"6": {"class_type": "VAEDecode", "inputs": {"samples": ["5", 0], "vae": ["1", 2]}},
"7": {"class_type": "SaveImage", "inputs": {"images": ["6", 0], "filename_prefix": "flux"}},
},
},
"MOSS-Image 文生图(内置)": {
"id": "builtin-moss",
"name": "MOSS-Image 文生图(内置)",
"builtin": True,
"updated": "2026-10-30 10:00",
"api": {
"1": {"class_type": "UNETLoader", "inputs": {"unet_name": "moss_image_sft_int8_convrot.safetensors", "weight_dtype": "default"}},
"2": {"class_type": "CLIPLoader", "inputs": {"clip_name": "qwen3.5_9b_w4a8_gptq.safetensors", "type": "moss_image", "device": "default"}},
"3": {"class_type": "CLIPTextEncode", "inputs": {"clip": ["2", 0], "text": "masterpiece, best quality"}},
"4": {"class_type": "CLIPTextEncode", "inputs": {"clip": ["2", 0], "text": "nsfw, worst quality, bad anatomy, watermark, jpeg artifact"}},
"5": {"class_type": "SkipLayerGuidanceDiTSimple", "inputs": {"model": ["1", 0], "double_layers": "",
"single_layers": "22", "start_percent": 0, "end_percent": 0.5}},
"6": {"class_type": "EmptyFlux2LatentImage", "inputs": {"width": 1024, "height": 1024, "batch_size": 1}},
"7": {"class_type": "KSampler", "inputs": {"model": ["5", 0], "positive": ["3", 0], "negative": ["4", 0],
"seed": 0, "steps": 25, "cfg": 2.5, "sampler_name": "er_sde",
"scheduler": "simple", "denoise": 1.0, "latent_image": ["6", 0]}},
"8": {"class_type": "VAEDecode", "inputs": {"samples": ["7", 0], "vae": ["9", 0]}},
"9": {"class_type": "VAELoader", "inputs": {"vae_name": "flux2-vae_small.safetensors"}},
"10": {"class_type": "SaveImage", "inputs": {"images": ["8", 0], "filename_prefix": "moss"}},
},
},
"FLUX 3 Klein 文生图(内置)": {
"id": "builtin-klein",
"name": "FLUX 3 Klein 文生图(内置)",
"builtin": True,
"updated": "2026-10-30 10:00",
"api": {
"1": {"class_type": "UNETLoader", "inputs": {"unet_name": "flux3-image-klein-int8-convrot.safetensors", "weight_dtype": "default"}},
"2": {"class_type": "CLIPLoader", "inputs": {"clip_name": "qwen3vl_4b_int8_convrot.safetensors", "type": "flux3", "device": "default"}},
"3": {"class_type": "CLIPTextEncode", "inputs": {"clip": ["2", 0], "text": "masterpiece, best quality"}},
"4": {"class_type": "EmptyFlux2LatentImage", "inputs": {"width": 1024, "height": 1024, "batch_size": 1}},
"5": {"class_type": "KSampler", "inputs": {"model": ["1", 0], "positive": ["3", 0], "negative": ["3", 0],
"seed": 0, "steps": 16, "cfg": 1.0, "sampler_name": "euler",
"scheduler": "simple", "denoise": 1.0, "latent_image": ["4", 0]}},
"6": {"class_type": "VAEDecode", "inputs": {"samples": ["5", 0], "vae": ["7", 0]}},
"7": {"class_type": "VAELoader", "inputs": {"vae_name": "flux2-vae.safetensors"}},
"8": {"class_type": "SaveImage", "inputs": {"images": ["6", 0], "filename_prefix": "flux3-klein"}},
},
},
"连通性测试(内置)": {
"id": "builtin-smoke",
"name": "连通性测试(内置)",
"builtin": True,
"updated": "2026-08-29 10:00",
"api": {
"1": {"class_type": "LoadImage", "inputs": {"image": "example.png", "upload": "image"}},
"2": {"class_type": "SaveImage", "inputs": {"images": ["1", 0], "filename_prefix": "agent_smoke"}},
},
},
}
# H3 档位元数据(实测值来自 minimax-h3-turing 研究会话,代码侧注入避免改动工作流 json 文件)
# tier: final=成片(同 seed 可复现) draft=草稿(T8 缓存命中致采样分叉,同 seed 不可复现)
WF_META = {
"builtin-flux": {"tier": "final", "est_min": 1.5},
"builtin-moss": {"tier": "final", "est_min": 2.0},
"builtin-klein": {"tier": "final", "est_min": 1.0},
"h3-t2v": {"tier": "final", "est_min": 4.7},
"h3-i2v": {"tier": "final", "est_min": 7.0},
"h3-t2v-t8draft": {"tier": "draft", "est_min": 2.7},
"h3-i2v-t8draft": {"tier": "draft", "est_min": 4.3},
"h3-t2v-pdd8-t8": {"tier": "draft", "est_min": 3.5},
}
# 草稿快跑映射:成片工作流 → 对应草稿档(PDD8 版需 master+PDD 权重,留手动选择)
DRAFT_MAP = {"h3-t2v": "h3-t2v-t8draft", "h3-i2v": "h3-i2v-t8draft"}
def list_workflows():
out = list(BUILTIN_WORKFLOWS.values())
for fn in os.listdir(WORKFLOW_DIR):
# .crashed. 归档(如 sage 崩溃版 h3_t2v.sage_cuda.crashed.json)只留档不入库——误跑会让 ComfyUI 原生崩溃
if fn.endswith(".json") and ".crashed." not in fn:
wf = read_json_file(os.path.join(WORKFLOW_DIR, fn), None)
if wf:
out.append(wf)
out.sort(key=lambda w: (w.get("builtin", False) is False, w.get("name", "")))
for w in out:
m = WF_META.get(w.get("id"))
if m:
w.update(m)
return out
def workflow_path(wid):
return os.path.join(WORKFLOW_DIR, safe_name(wid) + ".json")
# ---------------------------------------------------------------- UI -> API converter
LINK_TYPE_TOKENS = {"MODEL", "CLIP", "VAE", "CONDITIONING", "LATENT", "IMAGE", "MASK", "CONTROL_NET",
"SAMPLER", "SIGMAS", "NOISE", "GUIDER", "LATENT_KEYFRAME"}
# 前端专属节点:不进执行图
_SKIP_UI_TYPES = {"MarkdownNote", "Note"}
_IN_BORDER, _OUT_BORDER = -10, -20 # 子图输入/输出虚拟节点 id(官方约定)
_INNER_LNK_BASE, _BRIDGE_LNK_BASE = 100000, 200000 # 展开后内部连线/桥接连线的新 id 基址
def _flatten_subgraphs(ui):
"""展开 definitions.subgraphs 的引用节点为扁平执行图(单层;嵌套子图抛错)。
数据流:子图输入槽的外部值 → 内部终点(fan-out 复制);子图输出槽 → 主图消费者
(UUID 链式相连时递归解析到最终内部源)。widget 值留在子图内部 Primitive 节点上的
官方模板风格:widget 绑定连线忽略,Primitive 用自己的 widgets_values。"""
subdefs = {s.get("id"): s for s in (ui.get("definitions") or {}).get("subgraphs") or []}
if not subdefs:
return ui
def norm(l):
# 主图 links 为 list [id,o,os,t,ts,type];子图 links 为 dict
if isinstance(l, dict):
return [l["id"], l.get("origin_id"), l.get("origin_slot", 0),
l.get("target_id"), l.get("target_slot", 0), l.get("type", "*")]
return list(l)
instances = {} # uuid节点id -> 实例信息
out_nodes, out_links = [], []
pending = [] # (uuid_id, in_name, 终点id_str, 终点slot, type)
max_lid = max([l[0] for l in (ui.get("links") or [])] or [0])
for n in ui.get("nodes") or []:
if n.get("type") in _SKIP_UI_TYPES:
continue
if n.get("type") in subdefs:
sub = subdefs[n.get("type")]
inner = [x for x in sub.get("nodes") or [] if x.get("type") not in _SKIP_UI_TYPES]
if any(x.get("type") in subdefs for x in inner):
raise ValueError("嵌套子图暂不支持,请用 ComfyUI 前端导出 API 格式")
instances[n.get("id")] = {
"pref": f"{n.get('id')}x", "sub": sub, "inner": inner,
"in_by_name": {s.get("name"): s for s in sub.get("inputs") or []},
"out_by_idx": sub.get("outputs") or [],
"links": {norm(l)[0]: norm(l) for l in sub.get("links") or []},
"slot_default": {}, # 槽名 -> 从 widget 绑定端点提取的当前值
}
else:
out_nodes.append(n)
# 输出槽解析:UUID(id, slot) -> 最终实体 (id_str, slot)
def resolve_out(nid, slot):
inst = instances.get(nid)
if not inst:
return str(nid), slot
for L in (inst["out_by_idx"][slot].get("linkIds") or [] if slot < len(inst["out_by_idx"]) else []):
l = inst["links"].get(L)
if l and l[1] not in (_IN_BORDER, _OUT_BORDER):
return f"{inst['pref']}{l[1]}", l[2]
return None
def _is_widget_bind(l, inst):
"""子图输入槽 -> 内部节点 widget 的穿透线(值在节点自己的 widgets_values 上)。
UI json 把 widget 槽也列在 inputs 数组里(带 widget 标记),据此精确区分。"""
tgt = next((x for x in inst["inner"] if x.get("id") == l[3]), None)
if not tgt:
return True
t_ins = tgt.get("inputs") or []
if l[4] >= len(t_ins):
return True
return "widget" in t_ins[l[4]]
_PRIM_BY_TYPE = {"INT": "PrimitiveInt", "FLOAT": "PrimitiveFloat", "BOOLEAN": "PrimitiveBoolean", "STRING": "PrimitiveString"}
for inst in instances.values():
pref = inst["pref"]
# 槽默认值:widget 绑定端点承载了槽的当前值(UI 里外层 widget 是它的镜像)
for s in (inst["sub"].get("inputs") or []):
for L in s.get("linkIds") or []:
l = inst["links"].get(L)
if not l or l[1] != _IN_BORDER or not _is_widget_bind(l, inst):
continue
t = next((x for x in inst["inner"] if x.get("id") == l[3]), None)
if not t or not t.get("widgets_values"):
continue
widx = l[4] - sum(1 for i in (t.get("inputs") or [])[:l[4]] if "widget" not in i)
if 0 <= widx < len(t["widgets_values"]):
inst["slot_default"][s.get("name")] = t["widgets_values"][widx]
break
# widget 绑定线的 id 集合:引用直接清 None,让 schema 消费 widgets_values
wbound = {_INNER_LNK_BASE + l[0] for l in inst["links"].values() if l[1] == _IN_BORDER and _is_widget_bind(l, inst)}
for x in inst["inner"]:
c = dict(x)
c["id"] = f"{pref}{x.get('id')}"
for inp in c.get("inputs") or []:
if inp.get("link") is None:
continue
newl = _INNER_LNK_BASE + inp["link"]
inp["link"] = None if newl in wbound else newl
out_nodes.append(c)
for l in inst["links"].values():
if l[1] == _IN_BORDER:
if _is_widget_bind(l, inst):
continue # widget 绑定连线:值在节点 widgets_values 上
s_in = next((s for s in (inst["sub"].get("inputs") or []) if s.get("linkIds") and l[0] in s["linkIds"]), None)
if s_in:
pending.append((l, s_in, f"{pref}{l[3]}", l[4], l[5]))
continue
if l[3] == _OUT_BORDER:
continue
nid = _INNER_LNK_BASE + l[0]
out_links.append([nid, f"{pref}{l[1]}", l[2], f"{pref}{l[3]}", l[4], l[5]])
# 主图连线:实体→实体保留;目标/源头是 UUID 的转桥接
fed_slots = set() # (uuid_id, 槽名):已被主图连线/widget 值喂到的槽
for l in ui.get("links") or []:
src_is_uuid = l[1] in instances
tgt_is_uuid = l[3] in instances
if not src_is_uuid and not tgt_is_uuid:
out_links.append(list(l))
continue
if tgt_is_uuid:
u_in = next((i for i in next(n for n in ui["nodes"] if n.get("id") == l[3]).get("inputs") or []
if i.get("link") == l[0]), None)
if u_in:
fed_slots.add((l[3], u_in.get("name")))
s, sslot = (resolve_out(l[1], l[2]) if src_is_uuid else (str(l[1]), l[2]))
if s is None:
continue
# 找到该输入槽对应的内部终点
inst = instances[l[3]]
s_in = inst["in_by_name"].get(u_in.get("name"))
for L in (s_in or {}).get("linkIds") or []:
il = inst["links"].get(L)
if not il or il[1] != _IN_BORDER:
continue
if _is_widget_bind(il, inst):
continue
max_lid += 1
tid = f"{inst['pref']}{il[3]}"
out_links.append([max_lid, s, sslot, tid, il[4], l[5] or il[5]])
consumer = next((n for n in out_nodes if n.get("id") == tid), None)
if consumer and (consumer.get("inputs") or []) and il[4] < len(consumer["inputs"]):
consumer["inputs"][il[4]]["link"] = max_lid
continue
# 源是 UUID、目标是实体
s = resolve_out(l[1], l[2])
if s is None:
continue
max_lid += 1
out_links.append([max_lid, s[0], s[1], l[3], l[4], l[5]])
consumer = next((n for n in out_nodes if str(n.get("id")) == str(l[3])), None)
if consumer and (consumer.get("inputs") or []) and l[4] < len(consumer["inputs"]):
consumer["inputs"][l[4]]["link"] = max_lid
# 未被主图连线喂到的槽:其数据穿透端点改由 Primitive 节点承载槽默认值
for uuid_id, inst in instances.items():
pref = inst["pref"]
for s in (inst["sub"].get("inputs") or []):
sname = s.get("name")
if (uuid_id, sname) in fed_slots or sname not in inst["slot_default"]:
continue
# 只为真正有数据穿透端点的槽生成 Primitive(纯 widget 端点的槽值已在内部节点上)
data_tgts = [L for L in s.get("linkIds") or []
if (lambda l: l and l[1] == _IN_BORDER and not _is_widget_bind(l, inst))(inst["links"].get(L))]
if not data_tgts:
continue
ptype = _PRIM_BY_TYPE.get(s.get("type"))
if not ptype:
continue
pid = f"{pref}s_{sname}"
out_nodes.append({"id": pid, "type": ptype, "inputs": [],
"widgets_values": [inst["slot_default"][sname]]})
for L in s.get("linkIds") or []:
l = inst["links"].get(L)
if not l or l[1] != _IN_BORDER or _is_widget_bind(l, inst):
continue
max_lid += 1
tid = f"{pref}{l[3]}"
out_links.append([max_lid, pid, 0, tid, l[4], s.get("type")])
consumer = next((n for n in out_nodes if n.get("id") == tid), None)
if consumer and (consumer.get("inputs") or []) and l[4] < len(consumer["inputs"]):
consumer["inputs"][l[4]]["link"] = max_lid
# 未被主图连线覆盖的 pending(理论上主图连线已消费;此处兜底跳过)
return {"nodes": out_nodes, "links": out_links}
def convert_ui_to_api(ui, object_info):
"""ComfyUI 前端导出的 UI 格式 -> API(prompt) 格式。启发式映射 widgets_values。
支持 definitions.subgraphs 子图自动展开(官方 SCAIL-2 等新模板)。"""
if not isinstance(ui, dict) or "nodes" not in ui:
raise ValueError("不是 ComfyUI UI 格式(缺少 nodes)")
if (ui.get("definitions") or {}).get("subgraphs"):
ui = _flatten_subgraphs(ui)
links = {l[0]: l for l in ui.get("links", [])}
warnings = []
api = {}
for node in ui["nodes"]:
ntype = node.get("type", "")
if ntype in _SKIP_UI_TYPES:
continue
nid = str(node.get("id"))
schema = (object_info or {}).get(ntype)
ins_def = {}
if schema:
ins_def.update(schema.get("input", {}).get("required", {}) or {})
ins_def.update(schema.get("input", {}).get("optional", {}) or {})
api[nid] = {"class_type": ntype, "inputs": {}, "_pos": node.get("pos", [0, 0])}
# 1) 连线输入
for inp in node.get("inputs", []) or []:
lname = inp.get("name")
lid = inp.get("link")
if lid is None or lid not in links:
continue
l = links[lid]
api[nid]["inputs"][lname] = [str(l[1]), l[2]]
# 2) widget 标量输入:按 schema 顺序消费 widgets_values
wv = list(node.get("widgets_values", []) or [])
consumed = 0
for pname, pdef in ins_def.items():
if pname in api[nid]["inputs"]:
continue
if not isinstance(pdef, list) or not pdef:
continue
ptype = pdef[0]
if isinstance(ptype, str) and ptype in LINK_TYPE_TOKENS:
continue # 连线类型
if not wv:
break
val = wv.pop(0)
consumed += 1
api[nid]["inputs"][pname] = val
# seed 类 INT 自带 control_after_generate 下拉,多吃一个值
if ptype == "INT" and re.search(r"seed", pname, re.I) and wv and isinstance(wv[0], str) \
and wv[0] in ("fixed", "increment", "decrement", "randomize"):
wv.pop(0)
if wv:
warnings.append(f"节点{nid}({ntype}) 有 {len(wv)} 个未能映射的控件值,请检查参数")
return api, warnings
# ---------------------------------------------------------------- runs registry
def load_runs():
return read_json_file(RUNS_FILE, [])
_runs_lock = threading.RLock()
def add_run(run):
with _runs_lock:
runs = load_runs()
runs.insert(0, run)
write_json_file(RUNS_FILE, runs[:300])
def update_run(prompt_id, **kw):
with _runs_lock:
runs = load_runs()
for r in runs:
if r.get("prompt_id") == prompt_id:
r.update(kw)
break
write_json_file(RUNS_FILE, runs[:300])
# ---------------------------------------------------------------- obsidian
def vault_name():
return os.path.basename(SETTINGS["vault_path"].rstrip("\\/"))
def vault_dirs():
v = SETTINGS["vault_path"]
return (os.path.join(v, "ComfyAgent", "attachments"),
os.path.join(v, "ComfyAgent", "notes"),
os.path.join(v, "ComfyAgent", "workflows"))
def obsidian_uri(relpath):
q = urllib.parse.quote
return f"obsidian://open?vault={q(vault_name())}&file={q(relpath)}"
def obsidian_status():
v = SETTINGS["vault_path"]
valid = os.path.isdir(v)
att, notes, wfs = vault_dirs()
n_notes = len([f for f in os.listdir(notes) if f.endswith(".md")]) if os.path.isdir(notes) else 0