dsh-qqbot-muu 0.1.20 → 0.1.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/CHANGELOG.md +168 -154
  2. package/client/qqbot-settings.js +13401 -13380
  3. package/dist/config.js +573 -581
  4. package/dist/features/contextless-store.js +247 -247
  5. package/dist/features/four-source.js +338 -336
  6. package/dist/features/group-join-request.js +289 -287
  7. package/dist/features/local-models.js +1494 -1467
  8. package/dist/features/style-layer.js +501 -498
  9. package/dist/features/thinking-log.js +71 -69
  10. package/dist/gateway/bootstrap.js +1704 -1652
  11. package/dist/model/settings-reader.js +193 -102
  12. package/dist/shared/paths.js +128 -0
  13. package/dist/shared/settings-io.js +79 -83
  14. package/dshqqbot/.qqbot-extensions/inbound/00-vision.mjs +111 -0
  15. package/dshqqbot/.qqbot-extensions/inbound/aa-memory-recall.mjs +802 -794
  16. package/dshqqbot/.qqbot-extensions/inbound/az-feedback.mjs +113 -115
  17. package/dshqqbot/.qqbot-extensions/inbound/local-answer.mjs +689 -568
  18. package/dshqqbot/.qqbot-extensions/lib/local-llm.mjs +455 -444
  19. package/dshqqbot/.qqbot-extensions/lib/memory-agent.mjs +930 -928
  20. package/dshqqbot/.qqbot-extensions/lib/memory-core.mjs +537 -537
  21. package/dshqqbot/.qqbot-extensions/lib/memory-db.mjs +2476 -2245
  22. package/dshqqbot/.qqbot-extensions/lib/memory-hippo.mjs +18 -0
  23. package/dshqqbot/.qqbot-extensions/lib/memory.mjs +191 -186
  24. package/dshqqbot/.qqbot-extensions/lib/scope-util.mjs +84 -0
  25. package/dshqqbot/.qqbot-extensions/outbound/aa-sanitize.mjs +158 -154
  26. package/dshqqbot/.qqbot-extensions/outbound/memory-agent.mjs +121 -130
  27. package/dshqqbot/.qqbot-extensions/outbound/turn-memory.mjs +92 -101
  28. package/dshqqbot/.qqbot-extensions/tools/memory.mjs +178 -120
  29. package/dshqqbot/.qqbot-extensions/vendor/abogus/test-abogus.mjs +128 -126
  30. package/package.json +119 -118
  31. package/scripts/__pycache__/fan-mode.cpython-311.pyc +0 -0
  32. package/scripts/__pycache__/memory-audit.cpython-311.pyc +0 -0
  33. package/scripts/__pycache__/qq-ip-sync.cpython-311.pyc +0 -0
  34. package/scripts/__pycache__/qq-whitelist.cpython-311.pyc +0 -0
  35. package/scripts/ai-toolkit.py +607 -478
  36. package/scripts/chat-archive/__pycache__/build-sft-v4.cpython-311.pyc +0 -0
  37. package/scripts/chat-archive/__pycache__/build-sft.cpython-311.pyc +0 -0
  38. package/scripts/chat-archive/build-sft-v4.py +566 -0
  39. package/scripts/chat-archive/build-sft.py +390 -0
  40. package/scripts/chat-archive/eval-sft.py +155 -0
  41. package/scripts/chat-archive/extract-memory.py +143 -0
  42. package/scripts/chat-archive/inventory.py +182 -0
  43. package/scripts/chat-archive/merge-sft.py +114 -0
  44. package/scripts/chat-archive/qce-pull.py +217 -0
  45. package/scripts/chat-archive/qqheader.py +110 -0
  46. package/scripts/chat-archive/qqkey2.py +113 -0
  47. package/scripts/chat-archive/qqprobe.py +153 -0
  48. package/scripts/chat-archive/screen-collect.py +163 -0
  49. package/scripts/chat-archive/sqlcipher_probe.py +444 -0
  50. package/scripts/episode.py +529 -0
  51. package/scripts/fan-curve.py +218 -0
  52. package/scripts/fan-guard.cmd +8 -0
  53. package/scripts/fan-mode.py +380 -263
  54. package/scripts/gen-image.py +420 -413
  55. package/scripts/gen-video.py +186 -178
  56. package/scripts/hw-profile.py +175 -0
  57. package/scripts/media-enhance.py +402 -0
  58. package/scripts/memory-audit.py +581 -0
  59. package/scripts/migrate-scope.mjs +140 -139
  60. package/scripts/qq-connect-login.py +133 -0
  61. package/scripts/qq-ip-sync-hidden.vbs +5 -0
  62. package/scripts/qq-ip-sync.py +300 -0
  63. package/scripts/qq-whitelist.py +71 -0
  64. package/scripts/release-all.mjs +636 -509
  65. package/scripts/release-check.mjs +244 -226
  66. package/scripts/secure-room/index.html +334 -0
  67. package/scripts/secure-room/server.py +582 -0
  68. package/scripts/stickers/auto-tag.mjs +161 -0
  69. package/scripts/train/__pycache__/train-lora.cpython-311.pyc +0 -0
  70. package/scripts/train/gguf-quantize.py +92 -0
  71. package/scripts/train/gguf-to-hf.py +112 -0
  72. package/scripts/train/merge-lora.py +51 -0
  73. package/scripts/train/probe-mirrors.sh +12 -0
  74. package/scripts/train/probe-mirrors2.sh +20 -0
  75. package/scripts/train/setup-wsl.sh +23 -0
  76. package/scripts/train/setup-wsl2.sh +25 -0
  77. package/scripts/train/setup-wsl3.sh +22 -0
  78. package/scripts/train/setup-wsl4.sh +22 -0
  79. package/scripts/train/train-lora.py +319 -0
  80. package/dist/_backup_ctx_20261125_183653/dist/config.d.ts +0 -473
  81. package/dist/_backup_ctx_20261125_183653/dist/config.js +0 -450
  82. package/dist/_backup_ctx_20261125_183653/dist/features/contextless-trim.js +0 -304
  83. package/dist/_backup_ctx_20261125_183653/dist/session/session-manager.js +0 -1588
  84. package/dist/_backup_ctx_20261125_183653/dist/transport/inbound.js +0 -1567
  85. package/dist/_backup_ctx_20261125_183653/dist/transport/outbound.js +0 -647
  86. package/scripts/__pycache__/ai-mode.cpython-311.pyc +0 -0
  87. package/scripts/__pycache__/ai-toolkit.cpython-311.pyc +0 -0
  88. package/scripts/__pycache__/comfy_gen.cpython-311.pyc +0 -0
  89. package/scripts/__pycache__/gen-image.cpython-311.pyc +0 -0
  90. package/scripts/__pycache__/gen-video.cpython-311.pyc +0 -0
  91. package/scripts/__pycache__/model-registry.cpython-311.pyc +0 -0
  92. package/scripts/__pycache__/purge-standby.cpython-311.pyc +0 -0
@@ -1,413 +1,420 @@
1
- # -*- coding: utf-8 -*-
2
- """gen-image.py —— 本地出图(ComfyUI + FLUX.1-schnell GGUF),零云 token。
3
-
4
- 用法:
5
- python scripts/gen-image.py -p "a cat astronaut, cinematic" -o F:\\qqbot\\data\\out\\cat.png
6
- python scripts/gen-image.py -p "..." --w 1216 --h 832 --steps 4 --seed 42
7
- python scripts/gen-image.py -p "..." --start # 端口没起就先拉起来
8
- python scripts/gen-image.py --status # 只看服务状态
9
-
10
- 被谁调用:
11
- - 人:桌面「本地出图」快捷方式
12
- - DSH / qqbot:直接命令行或 HTTP(127.0.0.1:8191/prompt)
13
- 输出: 默认保存到 F:\\qqbot\\data\\out\\img-<时间戳>.png
14
- """
15
- import argparse
16
- import json
17
- import os
18
- import random
19
- import sys
20
- import time
21
- import urllib.parse
22
- import urllib.request
23
-
24
- HOST = os.environ.get("COMFY_URL", "http://127.0.0.1:8191")
25
- OLLAMA = os.environ.get("OLLAMA_URL", "http://127.0.0.1:11434")
26
- ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
27
-
28
-
29
- def out_dir(kind="image"):
30
- """统一产出目录(2026-11-28):F:\\qqbot\\out\\<kind>\\<yyyy-MM>\\ —— 和本地模型/SD 同一个出口。"""
31
- d = os.path.join(ROOT, "out", kind, time.strftime("%Y-%m"))
32
- os.makedirs(d, exist_ok=True)
33
- return d
34
-
35
- CLIP_L = "clip_l.safetensors"
36
- T5_Q5 = "t5-v1_1-xxl-encoder-Q5_K_M.gguf"
37
- T5_Q8 = "t5-v1_1-xxl-encoder-Q8_0.gguf"
38
- VAE = "ae.safetensors"
39
-
40
- # 模型档位:schnell=4 步快出;dev=Q4 起步;dev8/krea=Q8 画质档(2080Ti 22G 跑得下);
41
- # qwen=Qwen-Image-2512(20B DiT,Q4_K_M GGUF,中文/文字/审美明显强于 FLUX,慢一些)
42
- MODELS = {
43
- "schnell": {"unet": "flux1-schnell-Q6_K.gguf", "t5": T5_Q5,
44
- "steps": 4, "guidance": 0.0, "w": 1024, "h": 1024},
45
- "dev": {"unet": "flux1-dev-Q4_K_S.gguf", "t5": T5_Q5,
46
- "steps": 20, "guidance": 3.5, "w": 1216, "h": 832},
47
- "dev8": {"unet": "flux1-dev-Q8_0.gguf", "t5": T5_Q8,
48
- "steps": 24, "guidance": 3.5, "w": 1216, "h": 832},
49
- "krea": {"unet": "flux1-krea-dev-Q8_0.gguf", "t5": T5_Q8,
50
- "steps": 28, "guidance": 4.5, "w": 1216, "h": 832},
51
- "qwen": {"arch": "qwen", "unet": "qwen-image-2512-Q4_K_M.gguf",
52
- "te": "qwen_2.5_vl_7b_fp8_scaled.safetensors",
53
- "vae": "qwen_image_vae.safetensors",
54
- "steps": 20, "cfg": 2.5, "shift": 3.1, "w": 1024, "h": 1024},
55
- }
56
-
57
-
58
- def gpu_temp():
59
- """读一次显卡温度/风扇,读不到返回 None(不打扰主流程)。"""
60
- try:
61
- import subprocess
62
- out = subprocess.run(
63
- ["nvidia-smi", "--query-gpu=temperature.gpu,fan.speed", "--format=csv,noheader,nounits"],
64
- capture_output=True, text=True, timeout=10, creationflags=0x08000000)
65
- t, f = out.stdout.strip().split(",")
66
- return int(float(t)), int(float(f))
67
- except Exception:
68
- return None
69
-
70
-
71
- def cool_down(idle_temp=55):
72
- """任务结束回归:风扇回自动 + 卸模型 + 等降温。"""
73
- import subprocess
74
- script = os.path.join(ROOT, "scripts", "gpu-mode.py")
75
- if not os.path.exists(script):
76
- return
77
- print("[gen-image] 收尾:风扇回自动 + 卸显存 + 等温度 <= %dC ..." % idle_temp)
78
- try:
79
- subprocess.run([sys.executable, script, "--restore", "--idle-temp", str(idle_temp)],
80
- timeout=240, creationflags=0x08000000)
81
- except Exception as e:
82
- print("[gen-image] 收尾跳过: %s" % e)
83
-
84
-
85
- def task_boost():
86
- """任务开始:能提风扇就提(Afterburner),提不了就只提示散热。"""
87
- import subprocess
88
- script = os.path.join(ROOT, "scripts", "gpu-mode.py")
89
- if not os.path.exists(script):
90
- return
91
- try:
92
- subprocess.run([sys.executable, script, "--task"], timeout=30,
93
- creationflags=0x08000000)
94
- except Exception:
95
- pass
96
-
97
-
98
- def fan_task_again():
99
- """过热兜底:采样时发现风扇被打回日常档,就再用 fan-mode 压一次任务档。"""
100
- import subprocess
101
- script = os.path.join(ROOT, "scripts", "fan-mode.py")
102
- if not os.path.exists(script):
103
- return
104
- try:
105
- subprocess.run([sys.executable, script, "--task"], timeout=60,
106
- creationflags=0x08000000)
107
- except Exception as e:
108
- print("[gen-image] 重新压任务档失败: %s" % e)
109
-
110
-
111
- def http(path, data=None, timeout=30):
112
- url = HOST + path
113
- body = None
114
- headers = {}
115
- if data is not None:
116
- body = json.dumps(data).encode("utf-8")
117
- headers["Content-Type"] = "application/json"
118
- req = urllib.request.Request(url, data=body, headers=headers)
119
- with urllib.request.urlopen(req, timeout=timeout) as r:
120
- return r.read()
121
-
122
-
123
- def alive(timeout=3):
124
- try:
125
- http("/system_stats", timeout=timeout)
126
- return True
127
- except Exception:
128
- return False
129
-
130
-
131
- def ensure_started(wait_sec=180):
132
- if alive():
133
- return True
134
- runner = os.path.join(ROOT, "services", "comfyui", "run_comfy.py")
135
- if not os.path.exists(runner):
136
- print("[gen-image] ComfyUI 未运行,且找不到 %s" % runner)
137
- return False
138
- print("[gen-image] ComfyUI 未运行,正在后台启动(最多等 %ds)..." % wait_sec)
139
- # detached + run_comfy.py 自己写日志:WMI/wscript 那条路在非交互会话下会静默失败。
140
- # 只用 DETACHED_PROCESS(0x8),别叠加 CREATE_NO_WINDOW(语义冲突)。
141
- import subprocess
142
- try:
143
- subprocess.Popen([sys.executable, runner],
144
- creationflags=0x00000008,
145
- stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
146
- stderr=subprocess.DEVNULL, close_fds=True)
147
- except Exception as e:
148
- print("[gen-image] 拉起 ComfyUI 失败: %s" % e)
149
- return False
150
- t0 = time.time()
151
- while time.time() - t0 < wait_sec:
152
- time.sleep(3)
153
- if alive():
154
- print("[gen-image] ComfyUI 已就绪 (%.0fs)" % (time.time() - t0))
155
- return True
156
- print("[gen-image] 等待超时,看日志 F:\\qqbot\\logs\\comfyui8191.log")
157
- return False
158
-
159
-
160
- def free_ollama():
161
- """出图前把 Ollama 的模型请出显存(22GB 卡上 FLUX 要 ~11GB,叠不住)。"""
162
- try:
163
- with urllib.request.urlopen(OLLAMA + "/api/ps", timeout=3) as r:
164
- ps = json.loads(r.read().decode("utf-8"))
165
- for m in ps.get("models") or []:
166
- name = m.get("name") or m.get("model")
167
- if not name:
168
- continue
169
- req = urllib.request.Request(
170
- OLLAMA + "/api/generate",
171
- data=json.dumps({"model": name, "keep_alive": 0}).encode("utf-8"),
172
- headers={"Content-Type": "application/json"}, method="POST")
173
- try:
174
- urllib.request.urlopen(req, timeout=6).close()
175
- except Exception:
176
- pass
177
- except Exception:
178
- pass
179
-
180
-
181
- def build_workflow(prompt, neg, w, h, steps, seed, cfg, unet, guidance=0.0, t5=T5_Q5,
182
- init_name="", denoise=1.0):
183
- wf = {
184
- "1": {"class_type": "UnetLoaderGGUF", "inputs": {"unet_name": unet}},
185
- "2": {"class_type": "DualCLIPLoaderGGUF",
186
- "inputs": {"clip_name1": CLIP_L, "clip_name2": t5, "type": "flux"}},
187
- "3": {"class_type": "VAELoader", "inputs": {"vae_name": VAE}},
188
- "4": {"class_type": "CLIPTextEncode", "inputs": {"clip": ["2", 0], "text": prompt}},
189
- "5": {"class_type": "CLIPTextEncode", "inputs": {"clip": ["2", 0], "text": neg}},
190
- "6": {"class_type": "EmptySD3LatentImage",
191
- "inputs": {"width": w, "height": h, "batch_size": 1}},
192
- "7": {"class_type": "KSampler",
193
- "inputs": {"model": ["1", 0], "positive": ["4", 0], "negative": ["5", 0],
194
- "latent_image": ["6", 0], "seed": seed, "steps": steps,
195
- "cfg": cfg, "sampler_name": "euler", "scheduler": "simple",
196
- "denoise": 1.0}},
197
- "8": {"class_type": "VAEDecode", "inputs": {"samples": ["7", 0], "vae": ["3", 0]}},
198
- "9": {"class_type": "SaveImage",
199
- "inputs": {"images": ["8", 0], "filename_prefix": "qqbot/gen"}},
200
- }
201
- if guidance > 0:
202
- # FLUX dev 不是蒸馏模型:cfg 保持 1.0,真正的「提示词遵循强度」由 FluxGuidance
203
- # 注入到 conditioning 里(官方 dev 工作流就是 cfg=1 + guidance=3.5)。
204
- wf["10"] = {"class_type": "FluxGuidance",
205
- "inputs": {"conditioning": ["4", 0], "guidance": guidance}}
206
- wf["7"]["inputs"]["positive"] = ["10", 0]
207
- if init_name:
208
- # img2img(2026-11-29):同一角色换衣服/加细节时,用原立绘当底图,
209
- # denoise 越低越像原图(0.45~0.6 = 保留姿势与脸,只改衣服/质感)。
210
- wf["11"] = {"class_type": "LoadImage", "inputs": {"image": init_name}}
211
- wf["12"] = {"class_type": "VAEEncode", "inputs": {"pixels": ["11", 0], "vae": ["3", 0]}}
212
- wf["7"]["inputs"]["latent_image"] = ["12", 0]
213
- wf["7"]["inputs"]["denoise"] = float(denoise)
214
- return wf
215
-
216
-
217
- def build_qwen_workflow(prompt, neg, w, h, steps, seed, cfg, unet, te, vae, shift=3.1,
218
- init_name="", denoise=1.0):
219
- """Qwen-Image-2512(DiT,20B):UNET(GGUF) + qwen2.5-vl 文本塔 + qwen_image vae。
220
-
221
- 与 FLUX 的差别(别照抄 FLUX 那套):
222
- · 文本塔是 qwen_2.5_vl_7b,CLIPLoader 的 type 必须写 "qwen_image"(不是 flux)
223
- · 官方模板在 UNET 后接 ModelSamplingAuraFlow(shift=3.1),去掉它画面会发灰/过饱和
224
- · cfg 走真 classifier-free(2.5~3.0),**不用** FluxGuidance
225
- · 负向一般留空即可;中文提示词原生支持,不用硬翻英文
226
- """
227
- return {
228
- "1": {"class_type": "UnetLoaderGGUF", "inputs": {"unet_name": unet}},
229
- "2": {"class_type": "CLIPLoader",
230
- "inputs": {"clip_name": te, "type": "qwen_image", "device": "default"}},
231
- "3": {"class_type": "VAELoader", "inputs": {"vae_name": vae}},
232
- "4": {"class_type": "CLIPTextEncode", "inputs": {"clip": ["2", 0], "text": prompt}},
233
- "5": {"class_type": "CLIPTextEncode", "inputs": {"clip": ["2", 0], "text": neg}},
234
- "6": {"class_type": "EmptySD3LatentImage",
235
- "inputs": {"width": w, "height": h, "batch_size": 1}},
236
- "7": {"class_type": "ModelSamplingAuraFlow",
237
- "inputs": {"model": ["1", 0], "shift": shift}},
238
- "8": {"class_type": "KSampler",
239
- "inputs": {"model": ["7", 0], "positive": ["4", 0], "negative": ["5", 0],
240
- "latent_image": ["6", 0], "seed": seed, "steps": steps,
241
- "cfg": cfg, "sampler_name": "euler", "scheduler": "simple",
242
- "denoise": 1.0}},
243
- "9": {"class_type": "VAEDecode", "inputs": {"samples": ["8", 0], "vae": ["3", 0]}},
244
- "10": {"class_type": "SaveImage",
245
- "inputs": {"images": ["9", 0], "filename_prefix": "qqbot/gen"}},
246
- }
247
-
248
-
249
- def _with_img2img(wf, init_name, denoise, latent_node="6", sampler_node="8", vae_node="3", encode_id="11", load_id="12"):
250
- """把空 latent 换成「原图 → VAEEncode」,实现 img2img(保留角色与姿势)。"""
251
- if not init_name:
252
- return wf
253
- wf[load_id] = {"class_type": "LoadImage", "inputs": {"image": init_name}}
254
- wf[encode_id] = {"class_type": "VAEEncode", "inputs": {"pixels": [load_id, 0], "vae": [vae_node, 0]}}
255
- wf[sampler_node]["inputs"]["latent_image"] = [encode_id, 0]
256
- wf[sampler_node]["inputs"]["denoise"] = float(denoise)
257
- return wf
258
-
259
-
260
- def main():
261
- ap = argparse.ArgumentParser()
262
- ap.add_argument("-p", "--prompt", default="")
263
- ap.add_argument("-n", "--negative", default="")
264
- ap.add_argument("-o", "--out", default="")
265
- ap.add_argument("--w", type=int, default=0)
266
- ap.add_argument("--h", type=int, default=0)
267
- ap.add_argument("--model", choices=list(MODELS), default="schnell",
268
- help="schnell=4步快出;dev=Q4画质档;dev8=FLUX dev Q8 最高画质;"
269
- "krea=FLUX.1-Krea-dev Q8(审美更好);qwen=Qwen-Image-2512(中文/文字/审美最强)")
270
- ap.add_argument("--t5", default="", help="覆盖文本编码器(默认按模型档位自动选 Q5/Q8)")
271
- ap.add_argument("--steps", type=int, default=0)
272
- ap.add_argument("--cfg", type=float, default=0.0)
273
- ap.add_argument("--guidance", type=float, default=0.0,
274
- help="FLUX dev 的 FluxGuidance 强度,默认 3.5(schnell 不用)")
275
- ap.add_argument("--seed", type=int, default=-1)
276
- ap.add_argument("--init", default="", help="img2img 底图(本机路径);用于同一角色换衣服/加细节")
277
- ap.add_argument("--denoise", type=float, default=0.55, help="img2img 改动幅度:0.35 只修细节,0.6 换衣服,0.8 接近重画")
278
- ap.add_argument("--start", action="store_true")
279
- ap.add_argument("--status", action="store_true")
280
- ap.add_argument("--timeout", type=int, default=600)
281
- ap.add_argument("--no-cool", action="store_true", help="出完不自动冷却(连续批量出图时用)")
282
- ap.add_argument("--json", action="store_true", help="结束时打印一行 JSON(给 ai-toolkit / agent 解析)")
283
- a = ap.parse_args()
284
-
285
- prof = MODELS[a.model]
286
- is_qwen = prof.get("arch") == "qwen"
287
- is_dev = a.model != "schnell" and not is_qwen
288
- if a.steps <= 0:
289
- a.steps = prof["steps"]
290
- if a.cfg <= 0:
291
- # dev/krea 用 FluxGuidance(cfg 固定 1.0);qwen 走真 CFG
292
- a.cfg = 2.5 if is_qwen else 1.0
293
- if a.guidance <= 0 and is_dev:
294
- a.guidance = prof["guidance"]
295
- if a.w <= 0:
296
- a.w = prof["w"]
297
- if a.h <= 0:
298
- a.h = prof["h"]
299
- unet = prof["unet"]
300
- t5 = a.t5 or prof.get("t5", "")
301
-
302
- if a.status:
303
- ok = alive()
304
- print("comfyui %s -> %s" % (HOST, "UP" if ok else "DOWN"))
305
- if ok:
306
- print(http("/system_stats").decode("utf-8"))
307
- return 0 if ok else 1
308
-
309
- if not a.prompt:
310
- print("需要 -p 提示词(或 --status)")
311
- return 2
312
-
313
- if not (alive() or (a.start and ensure_started())):
314
- print("[gen-image] ComfyUI 不可用。先运行 F:\\qqbot\\services\\comfyui\\start_comfyui_8191.bat")
315
- return 3
316
-
317
- seed = a.seed if a.seed >= 0 else random.randint(1, 2 ** 31 - 1)
318
- free_ollama()
319
- task_boost()
320
- init_name = ""
321
- if a.init:
322
- # ComfyUI 的 LoadImage 只认它自己 input/ 目录里的文件名 → 先拷进去
323
- src = os.path.abspath(a.init)
324
- if not os.path.exists(src):
325
- print("[gen-image] 底图不存在: %s" % src)
326
- return 7
327
- in_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
328
- "services", "comfyui", "ComfyUI", "input")
329
- try:
330
- os.makedirs(in_dir, exist_ok=True)
331
- init_name = "qqbot-init-" + os.path.basename(src).replace(" ", "_")
332
- import shutil
333
- shutil.copyfile(src, os.path.join(in_dir, init_name))
334
- except Exception as e:
335
- print("[gen-image] 拷贝底图失败: %s" % e)
336
- return 7
337
- # 底图尺寸优先:img2img 时 latent 来自底图,--w/--h 不生效(枚举值仍会打日志)
338
- wf = (build_qwen_workflow(a.prompt, a.negative, a.w, a.h, a.steps, seed, a.cfg,
339
- unet, prof["te"], prof["vae"], prof.get("shift", 3.1))
340
- if is_qwen else
341
- build_workflow(a.prompt, a.negative, a.w, a.h, a.steps, seed, a.cfg, unet,
342
- a.guidance, t5))
343
- wf = _with_img2img(wf, init_name, a.denoise,
344
- sampler_node="8" if is_qwen else "7",
345
- vae_node="3", encode_id="13", load_id="14")
346
- cid = "gen-%d-%d" % (int(time.time()), random.randint(1000, 9999))
347
- resp = json.loads(http("/prompt", {"prompt": wf, "client_id": cid}).decode("utf-8"))
348
- pid = resp.get("prompt_id")
349
- if not pid:
350
- print("[gen-image] 提交失败: %s" % resp)
351
- return 4
352
- print("[gen-image] queued prompt_id=%s model=%s seed=%d size=%dx%d steps=%d cfg=%.1f"
353
- % (pid, a.model, seed, a.w, a.h, a.steps, a.cfg))
354
-
355
- t0 = time.time()
356
- hist = None
357
- peak_t = peak_f = 0
358
- last_sample = 0.0
359
- last_boost = t0
360
- while time.time() - t0 < a.timeout:
361
- time.sleep(2)
362
- if time.time() - last_sample > 8:
363
- last_sample = time.time()
364
- gt = gpu_temp()
365
- if gt:
366
- peak_t, peak_f = max(peak_t, gt[0]), max(peak_f, gt[1])
367
- if gt[0] >= 83:
368
- print("[gen-image] 温度 %dC 偏高(风扇 %d%%)" % gt)
369
- if gt[1] < 45 and time.time() - last_boost > 60:
370
- last_boost = time.time()
371
- fan_task_again()
372
- try:
373
- h = json.loads(http("/history/%s" % pid).decode("utf-8"))
374
- except Exception:
375
- continue
376
- if pid in h:
377
- hist = h[pid]
378
- break
379
- if not hist:
380
- print("[gen-image] 超时未完成,检查 F:\\qqbot\\logs\\comfyui8191.log")
381
- return 5
382
- if peak_t:
383
- print("[gen-image] 生成期间峰值温度 %dC / 风扇 %d%%" % (peak_t, peak_f))
384
-
385
- outs = hist.get("outputs", {})
386
- saved = []
387
- for node in outs.values():
388
- for img in node.get("images", []):
389
- q = ("/view?filename=%s&subfolder=%s&type=%s" %
390
- (urllib.parse.quote(img["filename"]), urllib.parse.quote(img.get("subfolder", "")),
391
- img.get("type", "output")))
392
- raw = http(q, timeout=60)
393
- path = a.out or os.path.join(out_dir("image"), "img-%s.png" % time.strftime("%Y%m%d-%H%M%S"))
394
- os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
395
- with open(path, "wb") as f:
396
- f.write(raw)
397
- saved.append(path)
398
- print("[gen-image] saved %s (%d KB)" % (path, len(raw) // 1024))
399
- if not saved:
400
- print("[gen-image] 完成但没有图片输出: %s" % json.dumps(outs, ensure_ascii=False)[:400])
401
- return 6
402
- if a.json:
403
- print(json.dumps({"ok": True, "model": a.model, "seed": seed, "width": a.w,
404
- "height": a.h, "steps": a.steps, "seconds": round(time.time() - t0, 1),
405
- "files": saved}, ensure_ascii=False))
406
- print("[gen-image] done in %.1fs" % (time.time() - t0))
407
- if not a.no_cool:
408
- cool_down()
409
- return 0
410
-
411
-
412
- if __name__ == "__main__":
413
- sys.exit(main())
1
+ # -*- coding: utf-8 -*-
2
+ """gen-image.py —— 本地出图(ComfyUI + FLUX.1-schnell GGUF),零云 token。
3
+
4
+ 用法:
5
+ python scripts/gen-image.py -p "a cat astronaut, cinematic" -o F:\\qqbot\\data\\out\\cat.png
6
+ python scripts/gen-image.py -p "..." --w 1216 --h 832 --steps 4 --seed 42
7
+ python scripts/gen-image.py -p "..." --start # 端口没起就先拉起来
8
+ python scripts/gen-image.py --status # 只看服务状态
9
+
10
+ 被谁调用:
11
+ - 人:桌面「本地出图」快捷方式
12
+ - DSH / qqbot:直接命令行或 HTTP(127.0.0.1:8191/prompt)
13
+ 输出: 默认保存到 F:\\qqbot\\data\\out\\img-<时间戳>.png
14
+ """
15
+ import argparse
16
+ import json
17
+ import os
18
+ import random
19
+ import sys
20
+ import time
21
+ import urllib.parse
22
+ import urllib.request
23
+
24
+ HOST = os.environ.get("COMFY_URL", "http://127.0.0.1:8191")
25
+ OLLAMA = os.environ.get("OLLAMA_URL", "http://127.0.0.1:11434")
26
+ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
27
+
28
+
29
+ def out_dir(kind="image"):
30
+ """统一产出目录(2026-11-28):F:\\qqbot\\out\\<kind>\\<yyyy-MM>\\ —— 和本地模型/SD 同一个出口。"""
31
+ d = os.path.join(ROOT, "out", kind, time.strftime("%Y-%m"))
32
+ os.makedirs(d, exist_ok=True)
33
+ return d
34
+
35
+ CLIP_L = "clip_l.safetensors"
36
+ T5_Q5 = "t5-v1_1-xxl-encoder-Q5_K_M.gguf"
37
+ T5_Q8 = "t5-v1_1-xxl-encoder-Q8_0.gguf"
38
+ VAE = "ae.safetensors"
39
+
40
+ # 模型档位:schnell=4 步快出;dev=Q4 起步;dev8/krea=Q8 画质档(2080Ti 22G 跑得下);
41
+ # qwen=Qwen-Image-2512(20B DiT,Q4_K_M GGUF,中文/文字/审美明显强于 FLUX,慢一些)
42
+ MODELS = {
43
+ "schnell": {"unet": "flux1-schnell-Q6_K.gguf", "t5": T5_Q5,
44
+ "steps": 4, "guidance": 0.0, "w": 1024, "h": 1024},
45
+ "dev": {"unet": "flux1-dev-Q4_K_S.gguf", "t5": T5_Q5,
46
+ "steps": 20, "guidance": 3.5, "w": 1216, "h": 832},
47
+ "dev8": {"unet": "flux1-dev-Q8_0.gguf", "t5": T5_Q8,
48
+ "steps": 24, "guidance": 3.5, "w": 1216, "h": 832},
49
+ "krea": {"unet": "flux1-krea-dev-Q8_0.gguf", "t5": T5_Q8,
50
+ "steps": 28, "guidance": 4.5, "w": 1216, "h": 832},
51
+ "qwen": {"arch": "qwen", "unet": "qwen-image-2512-Q4_K_M.gguf",
52
+ "te": "qwen_2.5_vl_7b_fp8_scaled.safetensors",
53
+ "vae": "qwen_image_vae.safetensors",
54
+ "steps": 20, "cfg": 2.5, "shift": 3.1, "w": 1024, "h": 1024},
55
+ }
56
+
57
+
58
+ def gpu_temp():
59
+ """读一次显卡温度/风扇,读不到返回 None(不打扰主流程)。"""
60
+ try:
61
+ import subprocess
62
+ out = subprocess.run(
63
+ ["nvidia-smi", "--query-gpu=temperature.gpu,fan.speed", "--format=csv,noheader,nounits"],
64
+ capture_output=True, text=True, timeout=10, creationflags=0x08000000)
65
+ t, f = out.stdout.strip().split(",")
66
+ return int(float(t)), int(float(f))
67
+ except Exception:
68
+ return None
69
+
70
+
71
+ def cool_down(idle_temp=55):
72
+ """任务结束回归:默认**不碰风扇**(只有显式开了 QQBOT_FAN_TASK 才成对恢复)。"""
73
+ if os.environ.get("QQBOT_FAN_TASK", "") not in ("1", "true", "yes", "on"):
74
+ return
75
+ import subprocess
76
+ script = os.path.join(ROOT, "scripts", "gpu-mode.py")
77
+ if not os.path.exists(script):
78
+ return
79
+ print("[gen-image] 收尾:风扇回自动 + 卸显存 + 等温度 <= %dC ..." % idle_temp)
80
+ try:
81
+ subprocess.run([sys.executable, script, "--restore", "--idle-temp", str(idle_temp)],
82
+ timeout=240, creationflags=0x08000000)
83
+ except Exception as e:
84
+ print("[gen-image] 收尾跳过: %s" % e)
85
+
86
+
87
+ def task_boost():
88
+ """任务开始:**默认不动风扇**(2026-12-02 主人反馈:空转风扇很吵,别替他做决定)。
89
+
90
+ 需要拉高风扇时显式给环境变量 QQBOT_FAN_TASK=1(或在自己脚本里先跑 fan-mode.py --task)。
91
+ """
92
+ if os.environ.get("QQBOT_FAN_TASK", "") not in ("1", "true", "yes", "on"):
93
+ return
94
+ import subprocess
95
+ script = os.path.join(ROOT, "scripts", "gpu-mode.py")
96
+ if not os.path.exists(script):
97
+ return
98
+ try:
99
+ subprocess.run([sys.executable, script, "--task"], timeout=30,
100
+ creationflags=0x08000000)
101
+ except Exception:
102
+ pass
103
+
104
+
105
+ def fan_task_again():
106
+ """过热兜底:采样时发现风扇被打回日常档,就再用 fan-mode 压一次任务档。"""
107
+ import subprocess
108
+ script = os.path.join(ROOT, "scripts", "fan-mode.py")
109
+ if not os.path.exists(script):
110
+ return
111
+ try:
112
+ subprocess.run([sys.executable, script, "--task"], timeout=60,
113
+ creationflags=0x08000000)
114
+ except Exception as e:
115
+ print("[gen-image] 重新压任务档失败: %s" % e)
116
+
117
+
118
+ def http(path, data=None, timeout=30):
119
+ url = HOST + path
120
+ body = None
121
+ headers = {}
122
+ if data is not None:
123
+ body = json.dumps(data).encode("utf-8")
124
+ headers["Content-Type"] = "application/json"
125
+ req = urllib.request.Request(url, data=body, headers=headers)
126
+ with urllib.request.urlopen(req, timeout=timeout) as r:
127
+ return r.read()
128
+
129
+
130
+ def alive(timeout=3):
131
+ try:
132
+ http("/system_stats", timeout=timeout)
133
+ return True
134
+ except Exception:
135
+ return False
136
+
137
+
138
+ def ensure_started(wait_sec=180):
139
+ if alive():
140
+ return True
141
+ runner = os.path.join(ROOT, "services", "comfyui", "run_comfy.py")
142
+ if not os.path.exists(runner):
143
+ print("[gen-image] ComfyUI 未运行,且找不到 %s" % runner)
144
+ return False
145
+ print("[gen-image] ComfyUI 未运行,正在后台启动(最多等 %ds)..." % wait_sec)
146
+ # detached + run_comfy.py 自己写日志:WMI/wscript 那条路在非交互会话下会静默失败。
147
+ # 只用 DETACHED_PROCESS(0x8),别叠加 CREATE_NO_WINDOW(语义冲突)。
148
+ import subprocess
149
+ try:
150
+ subprocess.Popen([sys.executable, runner],
151
+ creationflags=0x00000008,
152
+ stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
153
+ stderr=subprocess.DEVNULL, close_fds=True)
154
+ except Exception as e:
155
+ print("[gen-image] 拉起 ComfyUI 失败: %s" % e)
156
+ return False
157
+ t0 = time.time()
158
+ while time.time() - t0 < wait_sec:
159
+ time.sleep(3)
160
+ if alive():
161
+ print("[gen-image] ComfyUI 已就绪 (%.0fs)" % (time.time() - t0))
162
+ return True
163
+ print("[gen-image] 等待超时,看日志 F:\\qqbot\\logs\\comfyui8191.log")
164
+ return False
165
+
166
+
167
+ def free_ollama():
168
+ """出图前把 Ollama 的模型请出显存(22GB 卡上 FLUX 要 ~11GB,叠不住)。"""
169
+ try:
170
+ with urllib.request.urlopen(OLLAMA + "/api/ps", timeout=3) as r:
171
+ ps = json.loads(r.read().decode("utf-8"))
172
+ for m in ps.get("models") or []:
173
+ name = m.get("name") or m.get("model")
174
+ if not name:
175
+ continue
176
+ req = urllib.request.Request(
177
+ OLLAMA + "/api/generate",
178
+ data=json.dumps({"model": name, "keep_alive": 0}).encode("utf-8"),
179
+ headers={"Content-Type": "application/json"}, method="POST")
180
+ try:
181
+ urllib.request.urlopen(req, timeout=6).close()
182
+ except Exception:
183
+ pass
184
+ except Exception:
185
+ pass
186
+
187
+
188
+ def build_workflow(prompt, neg, w, h, steps, seed, cfg, unet, guidance=0.0, t5=T5_Q5,
189
+ init_name="", denoise=1.0):
190
+ wf = {
191
+ "1": {"class_type": "UnetLoaderGGUF", "inputs": {"unet_name": unet}},
192
+ "2": {"class_type": "DualCLIPLoaderGGUF",
193
+ "inputs": {"clip_name1": CLIP_L, "clip_name2": t5, "type": "flux"}},
194
+ "3": {"class_type": "VAELoader", "inputs": {"vae_name": VAE}},
195
+ "4": {"class_type": "CLIPTextEncode", "inputs": {"clip": ["2", 0], "text": prompt}},
196
+ "5": {"class_type": "CLIPTextEncode", "inputs": {"clip": ["2", 0], "text": neg}},
197
+ "6": {"class_type": "EmptySD3LatentImage",
198
+ "inputs": {"width": w, "height": h, "batch_size": 1}},
199
+ "7": {"class_type": "KSampler",
200
+ "inputs": {"model": ["1", 0], "positive": ["4", 0], "negative": ["5", 0],
201
+ "latent_image": ["6", 0], "seed": seed, "steps": steps,
202
+ "cfg": cfg, "sampler_name": "euler", "scheduler": "simple",
203
+ "denoise": 1.0}},
204
+ "8": {"class_type": "VAEDecode", "inputs": {"samples": ["7", 0], "vae": ["3", 0]}},
205
+ "9": {"class_type": "SaveImage",
206
+ "inputs": {"images": ["8", 0], "filename_prefix": "qqbot/gen"}},
207
+ }
208
+ if guidance > 0:
209
+ # FLUX dev 不是蒸馏模型:cfg 保持 1.0,真正的「提示词遵循强度」由 FluxGuidance
210
+ # 注入到 conditioning 里(官方 dev 工作流就是 cfg=1 + guidance=3.5)。
211
+ wf["10"] = {"class_type": "FluxGuidance",
212
+ "inputs": {"conditioning": ["4", 0], "guidance": guidance}}
213
+ wf["7"]["inputs"]["positive"] = ["10", 0]
214
+ if init_name:
215
+ # img2img(2026-11-29):同一角色换衣服/加细节时,用原立绘当底图,
216
+ # denoise 越低越像原图(0.45~0.6 = 保留姿势与脸,只改衣服/质感)。
217
+ wf["11"] = {"class_type": "LoadImage", "inputs": {"image": init_name}}
218
+ wf["12"] = {"class_type": "VAEEncode", "inputs": {"pixels": ["11", 0], "vae": ["3", 0]}}
219
+ wf["7"]["inputs"]["latent_image"] = ["12", 0]
220
+ wf["7"]["inputs"]["denoise"] = float(denoise)
221
+ return wf
222
+
223
+
224
+ def build_qwen_workflow(prompt, neg, w, h, steps, seed, cfg, unet, te, vae, shift=3.1,
225
+ init_name="", denoise=1.0):
226
+ """Qwen-Image-2512(DiT,20B):UNET(GGUF) + qwen2.5-vl 文本塔 + qwen_image vae。
227
+
228
+ 与 FLUX 的差别(别照抄 FLUX 那套):
229
+ · 文本塔是 qwen_2.5_vl_7b,CLIPLoader 的 type 必须写 "qwen_image"(不是 flux)
230
+ · 官方模板在 UNET 后接 ModelSamplingAuraFlow(shift=3.1),去掉它画面会发灰/过饱和
231
+ · cfg 走真 classifier-free(2.5~3.0),**不用** FluxGuidance
232
+ · 负向一般留空即可;中文提示词原生支持,不用硬翻英文
233
+ """
234
+ return {
235
+ "1": {"class_type": "UnetLoaderGGUF", "inputs": {"unet_name": unet}},
236
+ "2": {"class_type": "CLIPLoader",
237
+ "inputs": {"clip_name": te, "type": "qwen_image", "device": "default"}},
238
+ "3": {"class_type": "VAELoader", "inputs": {"vae_name": vae}},
239
+ "4": {"class_type": "CLIPTextEncode", "inputs": {"clip": ["2", 0], "text": prompt}},
240
+ "5": {"class_type": "CLIPTextEncode", "inputs": {"clip": ["2", 0], "text": neg}},
241
+ "6": {"class_type": "EmptySD3LatentImage",
242
+ "inputs": {"width": w, "height": h, "batch_size": 1}},
243
+ "7": {"class_type": "ModelSamplingAuraFlow",
244
+ "inputs": {"model": ["1", 0], "shift": shift}},
245
+ "8": {"class_type": "KSampler",
246
+ "inputs": {"model": ["7", 0], "positive": ["4", 0], "negative": ["5", 0],
247
+ "latent_image": ["6", 0], "seed": seed, "steps": steps,
248
+ "cfg": cfg, "sampler_name": "euler", "scheduler": "simple",
249
+ "denoise": 1.0}},
250
+ "9": {"class_type": "VAEDecode", "inputs": {"samples": ["8", 0], "vae": ["3", 0]}},
251
+ "10": {"class_type": "SaveImage",
252
+ "inputs": {"images": ["9", 0], "filename_prefix": "qqbot/gen"}},
253
+ }
254
+
255
+
256
+ def _with_img2img(wf, init_name, denoise, latent_node="6", sampler_node="8", vae_node="3", encode_id="11", load_id="12"):
257
+ """把空 latent 换成「原图 → VAEEncode」,实现 img2img(保留角色与姿势)。"""
258
+ if not init_name:
259
+ return wf
260
+ wf[load_id] = {"class_type": "LoadImage", "inputs": {"image": init_name}}
261
+ wf[encode_id] = {"class_type": "VAEEncode", "inputs": {"pixels": [load_id, 0], "vae": [vae_node, 0]}}
262
+ wf[sampler_node]["inputs"]["latent_image"] = [encode_id, 0]
263
+ wf[sampler_node]["inputs"]["denoise"] = float(denoise)
264
+ return wf
265
+
266
+
267
+ def main():
268
+ ap = argparse.ArgumentParser()
269
+ ap.add_argument("-p", "--prompt", default="")
270
+ ap.add_argument("-n", "--negative", default="")
271
+ ap.add_argument("-o", "--out", default="")
272
+ ap.add_argument("--w", type=int, default=0)
273
+ ap.add_argument("--h", type=int, default=0)
274
+ ap.add_argument("--model", choices=list(MODELS), default="schnell",
275
+ help="schnell=4步快出;dev=Q4画质档;dev8=FLUX dev Q8 最高画质;"
276
+ "krea=FLUX.1-Krea-dev Q8(审美更好);qwen=Qwen-Image-2512(中文/文字/审美最强)")
277
+ ap.add_argument("--t5", default="", help="覆盖文本编码器(默认按模型档位自动选 Q5/Q8)")
278
+ ap.add_argument("--steps", type=int, default=0)
279
+ ap.add_argument("--cfg", type=float, default=0.0)
280
+ ap.add_argument("--guidance", type=float, default=0.0,
281
+ help="FLUX dev 的 FluxGuidance 强度,默认 3.5(schnell 不用)")
282
+ ap.add_argument("--seed", type=int, default=-1)
283
+ ap.add_argument("--init", default="", help="img2img 底图(本机路径);用于同一角色换衣服/加细节")
284
+ ap.add_argument("--denoise", type=float, default=0.55, help="img2img 改动幅度:0.35 只修细节,0.6 换衣服,0.8 接近重画")
285
+ ap.add_argument("--start", action="store_true")
286
+ ap.add_argument("--status", action="store_true")
287
+ ap.add_argument("--timeout", type=int, default=600)
288
+ ap.add_argument("--no-cool", action="store_true", help="出完不自动冷却(连续批量出图时用)")
289
+ ap.add_argument("--json", action="store_true", help="结束时打印一行 JSON(给 ai-toolkit / agent 解析)")
290
+ a = ap.parse_args()
291
+
292
+ prof = MODELS[a.model]
293
+ is_qwen = prof.get("arch") == "qwen"
294
+ is_dev = a.model != "schnell" and not is_qwen
295
+ if a.steps <= 0:
296
+ a.steps = prof["steps"]
297
+ if a.cfg <= 0:
298
+ # dev/krea 用 FluxGuidance(cfg 固定 1.0);qwen 走真 CFG
299
+ a.cfg = 2.5 if is_qwen else 1.0
300
+ if a.guidance <= 0 and is_dev:
301
+ a.guidance = prof["guidance"]
302
+ if a.w <= 0:
303
+ a.w = prof["w"]
304
+ if a.h <= 0:
305
+ a.h = prof["h"]
306
+ unet = prof["unet"]
307
+ t5 = a.t5 or prof.get("t5", "")
308
+
309
+ if a.status:
310
+ ok = alive()
311
+ print("comfyui %s -> %s" % (HOST, "UP" if ok else "DOWN"))
312
+ if ok:
313
+ print(http("/system_stats").decode("utf-8"))
314
+ return 0 if ok else 1
315
+
316
+ if not a.prompt:
317
+ print("需要 -p 提示词(或 --status)")
318
+ return 2
319
+
320
+ if not (alive() or (a.start and ensure_started())):
321
+ print("[gen-image] ComfyUI 不可用。先运行 F:\\qqbot\\services\\comfyui\\start_comfyui_8191.bat")
322
+ return 3
323
+
324
+ seed = a.seed if a.seed >= 0 else random.randint(1, 2 ** 31 - 1)
325
+ free_ollama()
326
+ task_boost()
327
+ init_name = ""
328
+ if a.init:
329
+ # ComfyUI 的 LoadImage 只认它自己 input/ 目录里的文件名 → 先拷进去
330
+ src = os.path.abspath(a.init)
331
+ if not os.path.exists(src):
332
+ print("[gen-image] 底图不存在: %s" % src)
333
+ return 7
334
+ in_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
335
+ "services", "comfyui", "ComfyUI", "input")
336
+ try:
337
+ os.makedirs(in_dir, exist_ok=True)
338
+ init_name = "qqbot-init-" + os.path.basename(src).replace(" ", "_")
339
+ import shutil
340
+ shutil.copyfile(src, os.path.join(in_dir, init_name))
341
+ except Exception as e:
342
+ print("[gen-image] 拷贝底图失败: %s" % e)
343
+ return 7
344
+ # 底图尺寸优先:img2img 时 latent 来自底图,--w/--h 不生效(枚举值仍会打日志)
345
+ wf = (build_qwen_workflow(a.prompt, a.negative, a.w, a.h, a.steps, seed, a.cfg,
346
+ unet, prof["te"], prof["vae"], prof.get("shift", 3.1))
347
+ if is_qwen else
348
+ build_workflow(a.prompt, a.negative, a.w, a.h, a.steps, seed, a.cfg, unet,
349
+ a.guidance, t5))
350
+ wf = _with_img2img(wf, init_name, a.denoise,
351
+ sampler_node="8" if is_qwen else "7",
352
+ vae_node="3", encode_id="13", load_id="14")
353
+ cid = "gen-%d-%d" % (int(time.time()), random.randint(1000, 9999))
354
+ resp = json.loads(http("/prompt", {"prompt": wf, "client_id": cid}).decode("utf-8"))
355
+ pid = resp.get("prompt_id")
356
+ if not pid:
357
+ print("[gen-image] 提交失败: %s" % resp)
358
+ return 4
359
+ print("[gen-image] queued prompt_id=%s model=%s seed=%d size=%dx%d steps=%d cfg=%.1f"
360
+ % (pid, a.model, seed, a.w, a.h, a.steps, a.cfg))
361
+
362
+ t0 = time.time()
363
+ hist = None
364
+ peak_t = peak_f = 0
365
+ last_sample = 0.0
366
+ last_boost = t0
367
+ while time.time() - t0 < a.timeout:
368
+ time.sleep(2)
369
+ if time.time() - last_sample > 8:
370
+ last_sample = time.time()
371
+ gt = gpu_temp()
372
+ if gt:
373
+ peak_t, peak_f = max(peak_t, gt[0]), max(peak_f, gt[1])
374
+ if gt[0] >= 83:
375
+ print("[gen-image] 温度 %dC 偏高(风扇 %d%%)" % gt)
376
+ if gt[1] < 45 and time.time() - last_boost > 60:
377
+ last_boost = time.time()
378
+ fan_task_again()
379
+ try:
380
+ h = json.loads(http("/history/%s" % pid).decode("utf-8"))
381
+ except Exception:
382
+ continue
383
+ if pid in h:
384
+ hist = h[pid]
385
+ break
386
+ if not hist:
387
+ print("[gen-image] 超时未完成,检查 F:\\qqbot\\logs\\comfyui8191.log")
388
+ return 5
389
+ if peak_t:
390
+ print("[gen-image] 生成期间峰值温度 %dC / 风扇 %d%%" % (peak_t, peak_f))
391
+
392
+ outs = hist.get("outputs", {})
393
+ saved = []
394
+ for node in outs.values():
395
+ for img in node.get("images", []):
396
+ q = ("/view?filename=%s&subfolder=%s&type=%s" %
397
+ (urllib.parse.quote(img["filename"]), urllib.parse.quote(img.get("subfolder", "")),
398
+ img.get("type", "output")))
399
+ raw = http(q, timeout=60)
400
+ path = a.out or os.path.join(out_dir("image"), "img-%s.png" % time.strftime("%Y%m%d-%H%M%S"))
401
+ os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
402
+ with open(path, "wb") as f:
403
+ f.write(raw)
404
+ saved.append(path)
405
+ print("[gen-image] saved %s (%d KB)" % (path, len(raw) // 1024))
406
+ if not saved:
407
+ print("[gen-image] 完成但没有图片输出: %s" % json.dumps(outs, ensure_ascii=False)[:400])
408
+ return 6
409
+ if a.json:
410
+ print(json.dumps({"ok": True, "model": a.model, "seed": seed, "width": a.w,
411
+ "height": a.h, "steps": a.steps, "seconds": round(time.time() - t0, 1),
412
+ "files": saved}, ensure_ascii=False))
413
+ print("[gen-image] done in %.1fs" % (time.time() - t0))
414
+ if not a.no_cool:
415
+ cool_down()
416
+ return 0
417
+
418
+
419
+ if __name__ == "__main__":
420
+ sys.exit(main())