dsh-qqbot-muu 0.1.15 → 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 (171) hide show
  1. package/CHANGELOG.md +168 -85
  2. package/client/qqbot-settings.js +13401 -12024
  3. package/config/modules.json +212 -0
  4. package/dist/channel-tools.js +21 -10
  5. package/dist/config.d.ts +14 -0
  6. package/dist/config.js +573 -449
  7. package/dist/features/contextless-store.js +247 -247
  8. package/dist/features/contextless-trim.js +455 -34
  9. package/dist/features/four-source.js +338 -336
  10. package/dist/features/group-join-request.js +289 -287
  11. package/dist/features/local-models.js +1494 -0
  12. package/dist/features/rotate-summarizer.js +438 -0
  13. package/dist/features/scenario-detect.js +321 -0
  14. package/dist/features/scheduler.js +8 -1
  15. package/dist/features/session-rotate.js +499 -0
  16. package/dist/features/session-title.js +199 -0
  17. package/dist/features/style-layer.js +501 -0
  18. package/dist/features/thinking-log.js +71 -69
  19. package/dist/gateway/bootstrap.js +1704 -1388
  20. package/dist/gateway/data-root.js +77 -3
  21. package/dist/gateway/middleware-setup.js +6 -3
  22. package/dist/index.js +4 -2
  23. package/dist/model/settings-reader.js +193 -102
  24. package/dist/session/session-manager.js +1730 -1587
  25. package/dist/shared/paths.js +128 -0
  26. package/dist/shared/settings-io.js +79 -0
  27. package/dist/transport/inbound.js +20 -1
  28. package/dist/transport/outbound.js +56 -4
  29. package/docs/RELEASE_CHECKLIST.md +24 -2
  30. package/dshqqbot/.qqbot-extensions/hooks/interview-panel.mjs +41 -1
  31. package/dshqqbot/.qqbot-extensions/inbound/00-vision.mjs +111 -0
  32. package/dshqqbot/.qqbot-extensions/inbound/aa-memory-recall.mjs +802 -689
  33. package/dshqqbot/.qqbot-extensions/inbound/ac-image-see.mjs +1 -1
  34. package/dshqqbot/.qqbot-extensions/inbound/az-feedback.mjs +113 -115
  35. package/dshqqbot/.qqbot-extensions/inbound/local-answer.mjs +689 -568
  36. package/dshqqbot/.qqbot-extensions/lib/.pet-form.json +1 -1
  37. package/dshqqbot/.qqbot-extensions/lib/draw-core.mjs +238 -7
  38. package/dshqqbot/.qqbot-extensions/lib/local-llm.mjs +455 -394
  39. package/dshqqbot/.qqbot-extensions/lib/memory-agent.mjs +930 -928
  40. package/dshqqbot/.qqbot-extensions/lib/memory-core.mjs +537 -537
  41. package/dshqqbot/.qqbot-extensions/lib/memory-db.mjs +2476 -2245
  42. package/dshqqbot/.qqbot-extensions/lib/memory-hippo.mjs +18 -0
  43. package/dshqqbot/.qqbot-extensions/lib/memory.mjs +191 -186
  44. package/dshqqbot/.qqbot-extensions/lib/plugin-dir.mjs +14 -4
  45. package/dshqqbot/.qqbot-extensions/lib/scope-util.mjs +84 -0
  46. package/dshqqbot/.qqbot-extensions/lib/vision.mjs +1 -1
  47. package/dshqqbot/.qqbot-extensions/outbound/aa-sanitize.mjs +158 -154
  48. package/dshqqbot/.qqbot-extensions/outbound/ac-media-fix.mjs +5 -1
  49. package/dshqqbot/.qqbot-extensions/outbound/memory-agent.mjs +121 -130
  50. package/dshqqbot/.qqbot-extensions/outbound/split-reply.mjs +18 -2
  51. package/dshqqbot/.qqbot-extensions/outbound/turn-memory.mjs +92 -101
  52. package/dshqqbot/.qqbot-extensions/tools/draw.mjs +22 -1
  53. package/dshqqbot/.qqbot-extensions/tools/memory.mjs +178 -120
  54. package/dshqqbot/.qqbot-extensions/tools/pet_card.mjs +3 -2
  55. package/dshqqbot/.qqbot-extensions/tools/storyboard.mjs +3 -1
  56. package/dshqqbot/.qqbot-extensions/vendor/abogus/test-abogus.mjs +128 -126
  57. package/package.json +119 -111
  58. package/scripts/__pycache__/fan-mode.cpython-311.pyc +0 -0
  59. package/scripts/__pycache__/memory-audit.cpython-311.pyc +0 -0
  60. package/scripts/__pycache__/qq-ip-sync.cpython-311.pyc +0 -0
  61. package/scripts/__pycache__/qq-whitelist.cpython-311.pyc +0 -0
  62. package/scripts/_add_maintenance_cfg.py +20 -0
  63. package/scripts/_bench_keeplease.sh +10 -0
  64. package/scripts/_dbg_purge.py +15 -0
  65. package/scripts/_elev.sh +6 -0
  66. package/scripts/_fix_all_admin.cmd +16 -0
  67. package/scripts/_livecheck-image.mjs +33 -0
  68. package/scripts/_livecheck-llm.mjs +34 -0
  69. package/scripts/_livecheck-tts.mjs +37 -0
  70. package/scripts/_patch_curve.py +88 -0
  71. package/scripts/_patch_fan_thermal.py +24 -0
  72. package/scripts/_tag_tmp.py +13 -0
  73. package/scripts/adb-broker-client.mjs +87 -0
  74. package/scripts/adb-broker.mjs +205 -0
  75. package/scripts/ai-mode.cmd +6 -0
  76. package/scripts/ai-mode.py +387 -0
  77. package/scripts/ai-toolkit.py +607 -0
  78. package/scripts/apply-fan-gpu45.py +51 -0
  79. package/scripts/bench-fans.py +515 -0
  80. package/scripts/bench-load-direct.py +63 -0
  81. package/scripts/boot-tasks-hidden.vbs +20 -0
  82. package/scripts/boot-tasks.cmd +277 -0
  83. package/scripts/chat-archive/__pycache__/build-sft-v4.cpython-311.pyc +0 -0
  84. package/scripts/chat-archive/__pycache__/build-sft.cpython-311.pyc +0 -0
  85. package/scripts/chat-archive/build-sft-v4.py +566 -0
  86. package/scripts/chat-archive/build-sft.py +390 -0
  87. package/scripts/chat-archive/eval-sft.py +155 -0
  88. package/scripts/chat-archive/extract-memory.py +143 -0
  89. package/scripts/chat-archive/inventory.py +182 -0
  90. package/scripts/chat-archive/merge-sft.py +114 -0
  91. package/scripts/chat-archive/qce-pull.py +217 -0
  92. package/scripts/chat-archive/qqheader.py +110 -0
  93. package/scripts/chat-archive/qqkey2.py +113 -0
  94. package/scripts/chat-archive/qqprobe.py +153 -0
  95. package/scripts/chat-archive/screen-collect.py +163 -0
  96. package/scripts/chat-archive/sqlcipher_probe.py +444 -0
  97. package/scripts/comfy_gen.py +209 -0
  98. package/scripts/compose-video.py +168 -0
  99. package/scripts/dl_models.py +45 -0
  100. package/scripts/draw-now.cmd +18 -0
  101. package/scripts/dsh-instance-guard.mjs +20 -2
  102. package/scripts/elev-extra.cmd +25 -0
  103. package/scripts/episode.py +529 -0
  104. package/scripts/fan-curve.py +218 -0
  105. package/scripts/fan-guard.cmd +8 -0
  106. package/scripts/fan-mode.py +380 -0
  107. package/scripts/fan_manual_safe.py +33 -0
  108. package/scripts/fan_restore_manual.py +46 -0
  109. package/scripts/fc_curves.py +359 -0
  110. package/scripts/fix-fan-and-timers.cmd +39 -0
  111. package/scripts/fix_admin_all.py +94 -0
  112. package/scripts/flows.mjs +224 -0
  113. package/scripts/gateway.cmd +126 -0
  114. package/scripts/gen-image.py +420 -0
  115. package/scripts/gen-video.py +186 -0
  116. package/scripts/git-askpass.cmd +2 -2
  117. package/scripts/gpu-mode.py +195 -0
  118. package/scripts/hw-profile.py +175 -0
  119. package/scripts/install-schedule.cmd +37 -0
  120. package/scripts/install-watch.cmd +29 -0
  121. package/scripts/matte-cutout.py +106 -0
  122. package/scripts/media-enhance.py +402 -0
  123. package/scripts/memory-audit.py +581 -0
  124. package/scripts/migrate-scope.mjs +140 -139
  125. package/scripts/model-registry.py +519 -0
  126. package/scripts/openid-audit.mjs +219 -0
  127. package/scripts/pull-gguf.py +127 -0
  128. package/scripts/purge-standby.py +151 -0
  129. package/scripts/qq-connect-login.py +133 -0
  130. package/scripts/qq-ip-sync-hidden.vbs +5 -0
  131. package/scripts/qq-ip-sync.py +300 -0
  132. package/scripts/qq-login-once.cmd +20 -0
  133. package/scripts/qq-login-qr.py +72 -0
  134. package/scripts/qq-whitelist-fix.cmd +27 -0
  135. package/scripts/qq-whitelist-login.cmd +26 -0
  136. package/scripts/qq-whitelist.cmd +12 -0
  137. package/scripts/qq-whitelist.py +1452 -0
  138. package/scripts/quality-compare.py +134 -0
  139. package/scripts/release-all.mjs +636 -430
  140. package/scripts/release-check.mjs +244 -226
  141. package/scripts/resume-coder.cmd +38 -0
  142. package/scripts/secure-room/index.html +334 -0
  143. package/scripts/secure-room/server.py +582 -0
  144. package/scripts/security-check.mjs +164 -0
  145. package/scripts/selftest-local-llm.mjs +20 -0
  146. package/scripts/selftest-local-models.mjs +754 -0
  147. package/scripts/selftest-rotate-style.mjs +308 -0
  148. package/scripts/shutdown-s5-optional.cmd +21 -0
  149. package/scripts/sleep-2325.cmd +75 -0
  150. package/scripts/start-comfyui.cmd +5 -0
  151. package/scripts/start-strata.cmd +17 -0
  152. package/scripts/start-strata.vbs +11 -0
  153. package/scripts/start-watch-hidden.vbs +3 -0
  154. package/scripts/stickers/auto-tag.mjs +161 -0
  155. package/scripts/storage.mjs +236 -0
  156. package/scripts/sync-plugin-copies.mjs +98 -23
  157. package/scripts/tests/test-qq-whitelist.py +192 -0
  158. package/scripts/train/__pycache__/train-lora.cpython-311.pyc +0 -0
  159. package/scripts/train/gguf-quantize.py +92 -0
  160. package/scripts/train/gguf-to-hf.py +112 -0
  161. package/scripts/train/merge-lora.py +51 -0
  162. package/scripts/train/probe-mirrors.sh +12 -0
  163. package/scripts/train/probe-mirrors2.sh +20 -0
  164. package/scripts/train/setup-wsl.sh +23 -0
  165. package/scripts/train/setup-wsl2.sh +25 -0
  166. package/scripts/train/setup-wsl3.sh +22 -0
  167. package/scripts/train/setup-wsl4.sh +22 -0
  168. package/scripts/train/train-lora.py +319 -0
  169. package/scripts/vram-free.py +104 -0
  170. package/scripts/wechat-full-pull.mjs +1 -1
  171. package/settings-host.js +1047 -12
@@ -0,0 +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
+ """任务结束回归:默认**不碰风扇**(只有显式开了 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())
@@ -0,0 +1,186 @@
1
+ # -*- coding: utf-8 -*-
2
+ """gen-video.py —— 本地文生视频(ComfyUI + Wan2.2 TI2V-5B),零云 token。
3
+
4
+ 与 ComfyUI / HyperFrames 的分工(这就是「矛盾」的答案):
5
+ · ComfyUI(8191) = 像素工厂:出图(FLUX)、出视频(Wan2.2)。22GB 卡上跑得动。
6
+ · HyperFrames = 剪辑/合成层(转场、字幕、时间轴),吃的是已有素材。
7
+ · DSH = 调度:需要画面就调这里,需要成片编排再调 HyperFrames。
8
+ 三者不抢显存:谁上场前先跑 scripts\\vram-free.py。
9
+
10
+ 用法:
11
+ python scripts/gen-video.py -p "一只鲸鱼在城市上空游过,电影感" -o F:\\qqbot\\data\\out\\whale.mp4
12
+ python scripts/gen-video.py -p "..." --w 704 --h 480 --frames 49 --steps 20
13
+ python scripts/gen-video.py --status
14
+
15
+ 显存:5B fp16 + umt5 需要 ~20GB,ComfyUI 会自动切到 CPU 卸载;
16
+ 49 帧 704x480 在 2080 Ti 上大约几分钟,别用 121 帧试第一发。
17
+ """
18
+ import argparse
19
+ import json
20
+ import os
21
+ import random
22
+ import sys
23
+ import time
24
+ import urllib.parse
25
+ import urllib.request
26
+
27
+ HOST = os.environ.get("COMFY_URL", "http://127.0.0.1:8191")
28
+ OLLAMA = os.environ.get("OLLAMA_URL", "http://127.0.0.1:11434")
29
+ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
30
+
31
+
32
+ def out_dir(kind="video"):
33
+ """统一产出目录(2026-11-28):F:\\qqbot\\out\\<kind>\\<yyyy-MM>\\"""
34
+ d = os.path.join(ROOT, "out", kind, time.strftime("%Y-%m"))
35
+ os.makedirs(d, exist_ok=True)
36
+ return d
37
+
38
+ UNET = "wan2.2_ti2v_5B_fp16.safetensors"
39
+ TEXT_ENCODER = "umt5_xxl_fp16.safetensors"
40
+ VAE = "wan2.2_vae.safetensors"
41
+
42
+
43
+ def http(path, data=None, timeout=60):
44
+ req = urllib.request.Request(HOST + path, data=None if data is None else json.dumps(data).encode("utf-8"),
45
+ headers={} if data is None else {"Content-Type": "application/json"})
46
+ with urllib.request.urlopen(req, timeout=timeout) as r:
47
+ return r.read()
48
+
49
+
50
+ def alive():
51
+ try:
52
+ http("/system_stats", timeout=3)
53
+ return True
54
+ except Exception:
55
+ return False
56
+
57
+
58
+ def free_vram():
59
+ """出视频前先把 ComfyUI 里别的模型和 Ollama 全清掉。"""
60
+ try:
61
+ http("/free", {"unload_models": True, "free_memory": True}, timeout=10)
62
+ except Exception:
63
+ pass
64
+ try:
65
+ with urllib.request.urlopen(OLLAMA + "/api/ps", timeout=3) as r:
66
+ ps = json.loads(r.read().decode("utf-8"))
67
+ for m in ps.get("models") or []:
68
+ name = m.get("name") or m.get("model")
69
+ if not name:
70
+ continue
71
+ req = urllib.request.Request(
72
+ OLLAMA + "/api/generate",
73
+ data=json.dumps({"model": name, "keep_alive": 0}).encode("utf-8"),
74
+ headers={"Content-Type": "application/json"}, method="POST")
75
+ try:
76
+ urllib.request.urlopen(req, timeout=6).close()
77
+ except Exception:
78
+ pass
79
+ except Exception:
80
+ pass
81
+
82
+
83
+ def workflow(prompt, neg, w, h, frames, steps, seed, cfg, fps):
84
+ return {
85
+ "1": {"class_type": "UNETLoader", "inputs": {"unet_name": UNET, "weight_dtype": "default"}},
86
+ "2": {"class_type": "CLIPLoader", "inputs": {"clip_name": TEXT_ENCODER, "type": "wan"}},
87
+ "3": {"class_type": "VAELoader", "inputs": {"vae_name": VAE}},
88
+ "4": {"class_type": "ModelSamplingSD3", "inputs": {"model": ["1", 0], "shift": 8.0}},
89
+ "5": {"class_type": "CLIPTextEncode", "inputs": {"clip": ["2", 0], "text": prompt}},
90
+ "6": {"class_type": "CLIPTextEncode", "inputs": {"clip": ["2", 0], "text": neg}},
91
+ "7": {"class_type": "Wan22ImageToVideoLatent",
92
+ "inputs": {"vae": ["3", 0], "width": w, "height": h, "length": frames, "batch_size": 1}},
93
+ "8": {"class_type": "KSampler",
94
+ "inputs": {"model": ["4", 0], "positive": ["5", 0], "negative": ["6", 0],
95
+ "latent_image": ["7", 0], "seed": seed, "steps": steps, "cfg": cfg,
96
+ "sampler_name": "uni_pc", "scheduler": "simple", "denoise": 1.0}},
97
+ "9": {"class_type": "VAEDecode", "inputs": {"samples": ["8", 0], "vae": ["3", 0]}},
98
+ "10": {"class_type": "CreateVideo", "inputs": {"images": ["9", 0], "fps": fps}},
99
+ "11": {"class_type": "SaveVideo",
100
+ "inputs": {"video": ["10", 0], "filename_prefix": "qqbot/vid", "format": "mp4", "codec": "h264"}},
101
+ }
102
+
103
+
104
+ def main():
105
+ ap = argparse.ArgumentParser()
106
+ ap.add_argument("-p", "--prompt", default="")
107
+ ap.add_argument("-n", "--negative", default="色调艳丽, 过曝, 静态, 细节模糊不清, 字幕, 画面整体发灰")
108
+ ap.add_argument("-o", "--out", default="")
109
+ ap.add_argument("--w", type=int, default=704)
110
+ ap.add_argument("--h", type=int, default=480)
111
+ ap.add_argument("--frames", type=int, default=49)
112
+ ap.add_argument("--fps", type=float, default=24.0)
113
+ ap.add_argument("--steps", type=int, default=20)
114
+ ap.add_argument("--cfg", type=float, default=5.0)
115
+ ap.add_argument("--seed", type=int, default=-1)
116
+ ap.add_argument("--status", action="store_true")
117
+ ap.add_argument("--json", action="store_true", help="结束时打一行 JSON(给 ai-toolkit / agent 解析)")
118
+ ap.add_argument("--timeout", type=int, default=3600)
119
+ a = ap.parse_args()
120
+
121
+ if a.status:
122
+ print("comfyui %s -> %s" % (HOST, "UP" if alive() else "DOWN"))
123
+ return 0 if alive() else 1
124
+ if not a.prompt:
125
+ print("需要 -p 提示词(或 --status)")
126
+ return 2
127
+ if not alive():
128
+ print("[gen-video] ComfyUI 没起:先跑 F:\\qqbot\\services\\comfyui\\start_comfyui_8191.bat")
129
+ return 3
130
+
131
+ free_vram()
132
+ seed = a.seed if a.seed >= 0 else random.randint(1, 2 ** 31 - 1)
133
+ wf = workflow(a.prompt, a.negative, a.w, a.h, a.frames, a.steps, seed, a.cfg, a.fps)
134
+ cid = "vid-%d-%d" % (int(time.time()), random.randint(1000, 9999))
135
+ resp = json.loads(http("/prompt", {"prompt": wf, "client_id": cid}).decode("utf-8"))
136
+ pid = resp.get("prompt_id")
137
+ if not pid:
138
+ print("[gen-video] 提交失败: %s" % resp)
139
+ return 4
140
+ print("[gen-video] queued %s %dx%d %d帧 steps=%d seed=%d" % (pid, a.w, a.h, a.frames, a.steps, seed))
141
+
142
+ t0 = time.time()
143
+ hist = None
144
+ while time.time() - t0 < a.timeout:
145
+ time.sleep(5)
146
+ try:
147
+ h = json.loads(http("/history/%s" % pid).decode("utf-8"))
148
+ except Exception:
149
+ continue
150
+ if pid in h:
151
+ hist = h[pid]
152
+ break
153
+ if int(time.time() - t0) % 60 < 5:
154
+ print("[gen-video] ... %.0fs" % (time.time() - t0))
155
+ if not hist:
156
+ print("[gen-video] 超时,检查 F:\\qqbot\\logs\\comfyui8191.log")
157
+ return 5
158
+
159
+ for node in hist.get("outputs", {}).values():
160
+ for key in ("images", "videos", "gifs"):
161
+ for item in node.get(key, []) or []:
162
+ fn = item.get("filename")
163
+ if not fn:
164
+ continue
165
+ q = "/view?filename=%s&subfolder=%s&type=%s" % (
166
+ urllib.parse.quote(fn), urllib.parse.quote(item.get("subfolder", "")), item.get("type", "output"))
167
+ raw = http(q, timeout=180)
168
+ path = a.out or os.path.join(out_dir("video"), "vid-%s.mp4" % time.strftime("%Y%m%d-%H%M%S"))
169
+ os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
170
+ with open(path, "wb") as f:
171
+ f.write(raw)
172
+ ok = {"ok": True, "file": path, "files": [path], "model": "wan2.2-ti2v-5b",
173
+ "width": a.w, "height": a.h, "frames": a.frames, "fps": a.fps,
174
+ "steps": a.steps, "seed": seed,
175
+ "seconds": round(time.time() - t0, 1),
176
+ "mb": round(len(raw) / 1048576.0, 2)}
177
+ if a.json:
178
+ print(json.dumps(ok, ensure_ascii=False))
179
+ print("[gen-video] saved %s (%.1f MB) in %.0fs" % (path, len(raw) / 1048576.0, time.time() - t0))
180
+ return 0
181
+ print("[gen-video] 没有视频输出: %s" % json.dumps(hist.get("outputs", {}), ensure_ascii=False)[:400])
182
+ return 6
183
+
184
+
185
+ if __name__ == "__main__":
186
+ sys.exit(main())
@@ -1,2 +1,2 @@
1
- @echo off
2
- echo %QQBOT_GIT_TOKEN%
1
+ @echo off
2
+ echo %QQBOT_GIT_TOKEN%