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,178 +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("--timeout", type=int, default=3600)
118
- a = ap.parse_args()
119
-
120
- if a.status:
121
- print("comfyui %s -> %s" % (HOST, "UP" if alive() else "DOWN"))
122
- return 0 if alive() else 1
123
- if not a.prompt:
124
- print("需要 -p 提示词(或 --status)")
125
- return 2
126
- if not alive():
127
- print("[gen-video] ComfyUI 没起:先跑 F:\\qqbot\\services\\comfyui\\start_comfyui_8191.bat")
128
- return 3
129
-
130
- free_vram()
131
- seed = a.seed if a.seed >= 0 else random.randint(1, 2 ** 31 - 1)
132
- wf = workflow(a.prompt, a.negative, a.w, a.h, a.frames, a.steps, seed, a.cfg, a.fps)
133
- cid = "vid-%d-%d" % (int(time.time()), random.randint(1000, 9999))
134
- resp = json.loads(http("/prompt", {"prompt": wf, "client_id": cid}).decode("utf-8"))
135
- pid = resp.get("prompt_id")
136
- if not pid:
137
- print("[gen-video] 提交失败: %s" % resp)
138
- return 4
139
- print("[gen-video] queued %s %dx%d %d帧 steps=%d seed=%d" % (pid, a.w, a.h, a.frames, a.steps, seed))
140
-
141
- t0 = time.time()
142
- hist = None
143
- while time.time() - t0 < a.timeout:
144
- time.sleep(5)
145
- try:
146
- h = json.loads(http("/history/%s" % pid).decode("utf-8"))
147
- except Exception:
148
- continue
149
- if pid in h:
150
- hist = h[pid]
151
- break
152
- if int(time.time() - t0) % 60 < 5:
153
- print("[gen-video] ... %.0fs" % (time.time() - t0))
154
- if not hist:
155
- print("[gen-video] 超时,检查 F:\\qqbot\\logs\\comfyui8191.log")
156
- return 5
157
-
158
- for node in hist.get("outputs", {}).values():
159
- for key in ("images", "videos", "gifs"):
160
- for item in node.get(key, []) or []:
161
- fn = item.get("filename")
162
- if not fn:
163
- continue
164
- q = "/view?filename=%s&subfolder=%s&type=%s" % (
165
- urllib.parse.quote(fn), urllib.parse.quote(item.get("subfolder", "")), item.get("type", "output"))
166
- raw = http(q, timeout=180)
167
- path = a.out or os.path.join(out_dir("video"), "vid-%s.mp4" % time.strftime("%Y%m%d-%H%M%S"))
168
- os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
169
- with open(path, "wb") as f:
170
- f.write(raw)
171
- print("[gen-video] saved %s (%.1f MB) in %.0fs" % (path, len(raw) / 1048576.0, time.time() - t0))
172
- return 0
173
- print("[gen-video] 没有视频输出: %s" % json.dumps(hist.get("outputs", {}), ensure_ascii=False)[:400])
174
- return 6
175
-
176
-
177
- if __name__ == "__main__":
178
- sys.exit(main())
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())
@@ -0,0 +1,175 @@
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ hw-profile.py — 这台机器到底能跑到多大的本地模型?(小白也能看懂的上限推荐)
5
+
6
+ 为什么要有(2026-12-02 主人要求):
7
+ "有的用户拿核显 + 16G 内存跑 7B,理论能跑但也就那样" —— 所以不能只给"能/不能",
8
+ 要给「推荐档位 + 预期速度 + 不建议的原因」,并能一键写进 local-llm-config.json。
9
+
10
+ 用法:
11
+ python scripts/hw-profile.py # 只诊断 + 推荐
12
+ python scripts/hw-profile.py --write # 顺便把推荐写进扩展配置(自动备份)
13
+ python scripts/hw-profile.py --json # 机器可读
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import argparse
18
+ import ctypes
19
+ import json
20
+ import os
21
+ import shutil
22
+ import subprocess
23
+ import sys
24
+ import time
25
+
26
+ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
27
+ CFG = os.path.join(ROOT, 'dshqqbot', '.qqbot-extensions', 'local-llm-config.json')
28
+
29
+
30
+ def sh(cmd: list[str], timeout=8) -> str:
31
+ try:
32
+ r = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout,
33
+ creationflags=0x08000000)
34
+ return (r.stdout or '').strip()
35
+ except Exception:
36
+ return ''
37
+
38
+
39
+ def gpu_info() -> list[dict]:
40
+ out = []
41
+ txt = sh(['nvidia-smi', '--query-gpu=name,memory.total,memory.used', '--format=csv,noheader,nounits'])
42
+ for line in txt.splitlines():
43
+ parts = [p.strip() for p in line.split(',')]
44
+ if len(parts) >= 2:
45
+ try:
46
+ out.append({'name': parts[0], 'vram_mb': int(float(parts[1])),
47
+ 'used_mb': int(float(parts[2])) if len(parts) > 2 else None})
48
+ except ValueError:
49
+ pass
50
+ if not out:
51
+ # 没有 nvidia-smi:看看是不是 AMD/Intel/核显
52
+ w = sh(['powershell', '-NoProfile', '-Command',
53
+ "Get-CimInstance Win32_VideoController | Select-Object -ExpandProperty Name"])
54
+ out = [{'name': n.strip(), 'vram_mb': 0, 'used_mb': None, 'integrated': True}
55
+ for n in w.splitlines() if n.strip()]
56
+ return out
57
+
58
+
59
+ def ram_gb() -> float:
60
+ class MEMORYSTATUSEX(ctypes.Structure):
61
+ _fields_ = [('dwLength', ctypes.c_ulong), ('dwMemoryLoad', ctypes.c_ulong),
62
+ ('ullTotalPhys', ctypes.c_ulonglong), ('ullAvailPhys', ctypes.c_ulonglong),
63
+ ('ullTotalPageFile', ctypes.c_ulonglong), ('ullAvailPageFile', ctypes.c_ulonglong),
64
+ ('ullTotalVirtual', ctypes.c_ulonglong), ('ullAvailVirtual', ctypes.c_ulonglong),
65
+ ('ullAvailExtendedVirtual', ctypes.c_ulonglong)]
66
+ m = MEMORYSTATUSEX()
67
+ m.dwLength = ctypes.sizeof(MEMORYSTATUSEX)
68
+ ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(m))
69
+ return round(m.ullTotalPhys / 1024 ** 3, 1)
70
+
71
+
72
+ def ollama_models() -> list[str]:
73
+ try:
74
+ import urllib.request
75
+ j = json.loads(urllib.request.urlopen('http://127.0.0.1:11434/api/tags', timeout=3).read())
76
+ return [m['name'] for m in j.get('models', [])]
77
+ except Exception:
78
+ return []
79
+
80
+
81
+ def recommend(vram_gb: float, ram: float, integrated: bool) -> dict:
82
+ """返回推荐档位。经验值,按 Q4_K_M 量化、2048 上下文估。"""
83
+ if integrated or vram_gb <= 0:
84
+ if ram >= 32:
85
+ return dict(tier='CPU/核显·保守', params='3B', quant='Q4_K_M',
86
+ speed='约 4~8 tok/s(纯 CPU)', model_hint='qwen2.5:3b',
87
+ note='核显/无独显:7B 也能"跑起来",但 2~4 tok/s、风扇狂转、聊两句就卡;建议 3B 或直接用云')
88
+ if ram >= 16:
89
+ return dict(tier='CPU/核显·最低', params='1.5B~3B', quant='Q4_K_M',
90
+ speed='约 2~5 tok/s', model_hint='qwen2.5:1.5b',
91
+ note='16G 内存 + 核显:7B 理论可跑但体验很差(每次回复 30s+),只适合极简短句')
92
+ return dict(tier='不建议本地', params='—', quant='—', speed='—', model_hint='',
93
+ note='内存 <16G:本地 7B 会频繁换页,建议直接用云端')
94
+ if vram_gb >= 20:
95
+ return dict(tier='旗舰', params='32B~35B(MoE)', quant='Q4', speed='约 20~40 tok/s',
96
+ model_hint='qwen3.6-35b-a3b', note='可常驻大模型;注意与 TTS/出图抢显存')
97
+ if vram_gb >= 14:
98
+ return dict(tier='高', params='14B', quant='Q4_K_M', speed='约 15~25 tok/s',
99
+ model_hint='qwen2.5:14b', note='14B 性价比最高的一档,性格/常识都不错')
100
+ if vram_gb >= 10:
101
+ return dict(tier='中高', params='8B~9B', quant='Q5_K_M', speed='约 25~40 tok/s',
102
+ model_hint='qwen3:8b', note='8B Q5 比 Q4 更稳,显存刚好够')
103
+ if vram_gb >= 7:
104
+ return dict(tier='中', params='7B~8B', quant='Q4_K_M', speed='约 25~45 tok/s',
105
+ model_hint='qwen3:8b', note='7/8B Q4 是甜点档,聊天足够')
106
+ if vram_gb >= 5:
107
+ return dict(tier='入门', params='3B~4B', quant='Q4_K_M', speed='约 30~50 tok/s',
108
+ model_hint='qwen2.5:3b', note='显存 5~7G:4B 刚好,7B 会溢出到内存变慢')
109
+ return dict(tier='入门', params='1.5B~3B', quant='Q4_K_M', speed='约 40~60 tok/s',
110
+ model_hint='qwen2.5:1.5b', note='显存 <5G:只建议 3B 以下')
111
+
112
+
113
+ def main():
114
+ ap = argparse.ArgumentParser()
115
+ ap.add_argument('--json', action='store_true')
116
+ ap.add_argument('--write', action='store_true')
117
+ a = ap.parse_args()
118
+
119
+ gpus = gpu_info()
120
+ ram = ram_gb()
121
+ best = max(gpus, key=lambda g: g.get('vram_mb') or 0) if gpus else {'name': '未知', 'vram_mb': 0}
122
+ vram = round((best.get('vram_mb') or 0) / 1024, 1)
123
+ rec = recommend(vram, ram, bool(best.get('integrated')) or vram <= 0)
124
+ models = ollama_models()
125
+ rep = {
126
+ 'at': time.strftime('%Y-%m-%d %H:%M:%S'),
127
+ 'cpu_cores': os.cpu_count(),
128
+ 'ram_gb': ram,
129
+ 'gpus': gpus,
130
+ 'vram_gb': vram,
131
+ 'recommend': rec,
132
+ 'ollama_models': models,
133
+ 'fits': [m for m in models if rec.get('model_hint') and rec['model_hint'].split(':')[0] in m],
134
+ }
135
+ if a.json:
136
+ print(json.dumps(rep, ensure_ascii=False, indent=2))
137
+ else:
138
+ print('=' * 56)
139
+ print('本机硬件画像 ' + rep['at'])
140
+ print('=' * 56)
141
+ print(f"CPU 核心 {rep['cpu_cores']} | 内存 {ram} GB")
142
+ for g in gpus:
143
+ print(f"显卡 {g.get('name')} " + (f"{round((g.get('vram_mb') or 0)/1024,1)} GB 显存" if g.get('vram_mb') else '(共享/核显)'))
144
+ r = rec
145
+ print('\n推荐档位:' + r['tier'] + f" → {r['params']} {r['quant']}")
146
+ print('预期速度:' + r['speed'])
147
+ print('参考模型:' + (r['model_hint'] or '—'))
148
+ print('说明:' + r['note'])
149
+ if models:
150
+ print('\n本机 ollama 已有:' + ', '.join(models[:10]))
151
+ if a.write:
152
+ try:
153
+ cfg = json.load(open(CFG, encoding='utf-8'))
154
+ except Exception:
155
+ cfg = {}
156
+ bak = CFG + '.bak-' + time.strftime('%Y%m%d-%H%M%S')
157
+ try:
158
+ shutil.copy2(CFG, bak)
159
+ except Exception:
160
+ pass
161
+ cfg['_hw_recommend'] = rec
162
+ cfg['_hw_checked_at'] = rep['at']
163
+ if models and rec.get('model_hint'):
164
+ hit = [m for m in models if rec['model_hint'].split(':')[0] in m]
165
+ if hit:
166
+ cfg['provider'] = 'ollama'
167
+ cfg['baseUrl'] = 'http://127.0.0.1:11434'
168
+ cfg['model'] = hit[0]
169
+ json.dump(cfg, open(CFG, 'w', encoding='utf-8'), ensure_ascii=False, indent=2)
170
+ print('\n已写入配置(备份 ' + os.path.basename(bak) + '):model=' + str(cfg.get('model')))
171
+ return 0
172
+
173
+
174
+ if __name__ == '__main__':
175
+ sys.exit(main())