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.
- package/CHANGELOG.md +168 -85
- package/client/qqbot-settings.js +13401 -12024
- package/config/modules.json +212 -0
- package/dist/channel-tools.js +21 -10
- package/dist/config.d.ts +14 -0
- package/dist/config.js +573 -449
- package/dist/features/contextless-store.js +247 -247
- package/dist/features/contextless-trim.js +455 -34
- package/dist/features/four-source.js +338 -336
- package/dist/features/group-join-request.js +289 -287
- package/dist/features/local-models.js +1494 -0
- package/dist/features/rotate-summarizer.js +438 -0
- package/dist/features/scenario-detect.js +321 -0
- package/dist/features/scheduler.js +8 -1
- package/dist/features/session-rotate.js +499 -0
- package/dist/features/session-title.js +199 -0
- package/dist/features/style-layer.js +501 -0
- package/dist/features/thinking-log.js +71 -69
- package/dist/gateway/bootstrap.js +1704 -1388
- package/dist/gateway/data-root.js +77 -3
- package/dist/gateway/middleware-setup.js +6 -3
- package/dist/index.js +4 -2
- package/dist/model/settings-reader.js +193 -102
- package/dist/session/session-manager.js +1730 -1587
- package/dist/shared/paths.js +128 -0
- package/dist/shared/settings-io.js +79 -0
- package/dist/transport/inbound.js +20 -1
- package/dist/transport/outbound.js +56 -4
- package/docs/RELEASE_CHECKLIST.md +24 -2
- package/dshqqbot/.qqbot-extensions/hooks/interview-panel.mjs +41 -1
- package/dshqqbot/.qqbot-extensions/inbound/00-vision.mjs +111 -0
- package/dshqqbot/.qqbot-extensions/inbound/aa-memory-recall.mjs +802 -689
- package/dshqqbot/.qqbot-extensions/inbound/ac-image-see.mjs +1 -1
- package/dshqqbot/.qqbot-extensions/inbound/az-feedback.mjs +113 -115
- package/dshqqbot/.qqbot-extensions/inbound/local-answer.mjs +689 -568
- package/dshqqbot/.qqbot-extensions/lib/.pet-form.json +1 -1
- package/dshqqbot/.qqbot-extensions/lib/draw-core.mjs +238 -7
- package/dshqqbot/.qqbot-extensions/lib/local-llm.mjs +455 -394
- package/dshqqbot/.qqbot-extensions/lib/memory-agent.mjs +930 -928
- package/dshqqbot/.qqbot-extensions/lib/memory-core.mjs +537 -537
- package/dshqqbot/.qqbot-extensions/lib/memory-db.mjs +2476 -2245
- package/dshqqbot/.qqbot-extensions/lib/memory-hippo.mjs +18 -0
- package/dshqqbot/.qqbot-extensions/lib/memory.mjs +191 -186
- package/dshqqbot/.qqbot-extensions/lib/plugin-dir.mjs +14 -4
- package/dshqqbot/.qqbot-extensions/lib/scope-util.mjs +84 -0
- package/dshqqbot/.qqbot-extensions/lib/vision.mjs +1 -1
- package/dshqqbot/.qqbot-extensions/outbound/aa-sanitize.mjs +158 -154
- package/dshqqbot/.qqbot-extensions/outbound/ac-media-fix.mjs +5 -1
- package/dshqqbot/.qqbot-extensions/outbound/memory-agent.mjs +121 -130
- package/dshqqbot/.qqbot-extensions/outbound/split-reply.mjs +18 -2
- package/dshqqbot/.qqbot-extensions/outbound/turn-memory.mjs +92 -101
- package/dshqqbot/.qqbot-extensions/tools/draw.mjs +22 -1
- package/dshqqbot/.qqbot-extensions/tools/memory.mjs +178 -120
- package/dshqqbot/.qqbot-extensions/tools/pet_card.mjs +3 -2
- package/dshqqbot/.qqbot-extensions/tools/storyboard.mjs +3 -1
- package/dshqqbot/.qqbot-extensions/vendor/abogus/test-abogus.mjs +128 -126
- package/package.json +119 -111
- package/scripts/__pycache__/fan-mode.cpython-311.pyc +0 -0
- package/scripts/__pycache__/memory-audit.cpython-311.pyc +0 -0
- package/scripts/__pycache__/qq-ip-sync.cpython-311.pyc +0 -0
- package/scripts/__pycache__/qq-whitelist.cpython-311.pyc +0 -0
- package/scripts/_add_maintenance_cfg.py +20 -0
- package/scripts/_bench_keeplease.sh +10 -0
- package/scripts/_dbg_purge.py +15 -0
- package/scripts/_elev.sh +6 -0
- package/scripts/_fix_all_admin.cmd +16 -0
- package/scripts/_livecheck-image.mjs +33 -0
- package/scripts/_livecheck-llm.mjs +34 -0
- package/scripts/_livecheck-tts.mjs +37 -0
- package/scripts/_patch_curve.py +88 -0
- package/scripts/_patch_fan_thermal.py +24 -0
- package/scripts/_tag_tmp.py +13 -0
- package/scripts/adb-broker-client.mjs +87 -0
- package/scripts/adb-broker.mjs +205 -0
- package/scripts/ai-mode.cmd +6 -0
- package/scripts/ai-mode.py +387 -0
- package/scripts/ai-toolkit.py +607 -0
- package/scripts/apply-fan-gpu45.py +51 -0
- package/scripts/bench-fans.py +515 -0
- package/scripts/bench-load-direct.py +63 -0
- package/scripts/boot-tasks-hidden.vbs +20 -0
- package/scripts/boot-tasks.cmd +277 -0
- package/scripts/chat-archive/__pycache__/build-sft-v4.cpython-311.pyc +0 -0
- package/scripts/chat-archive/__pycache__/build-sft.cpython-311.pyc +0 -0
- package/scripts/chat-archive/build-sft-v4.py +566 -0
- package/scripts/chat-archive/build-sft.py +390 -0
- package/scripts/chat-archive/eval-sft.py +155 -0
- package/scripts/chat-archive/extract-memory.py +143 -0
- package/scripts/chat-archive/inventory.py +182 -0
- package/scripts/chat-archive/merge-sft.py +114 -0
- package/scripts/chat-archive/qce-pull.py +217 -0
- package/scripts/chat-archive/qqheader.py +110 -0
- package/scripts/chat-archive/qqkey2.py +113 -0
- package/scripts/chat-archive/qqprobe.py +153 -0
- package/scripts/chat-archive/screen-collect.py +163 -0
- package/scripts/chat-archive/sqlcipher_probe.py +444 -0
- package/scripts/comfy_gen.py +209 -0
- package/scripts/compose-video.py +168 -0
- package/scripts/dl_models.py +45 -0
- package/scripts/draw-now.cmd +18 -0
- package/scripts/dsh-instance-guard.mjs +20 -2
- package/scripts/elev-extra.cmd +25 -0
- package/scripts/episode.py +529 -0
- package/scripts/fan-curve.py +218 -0
- package/scripts/fan-guard.cmd +8 -0
- package/scripts/fan-mode.py +380 -0
- package/scripts/fan_manual_safe.py +33 -0
- package/scripts/fan_restore_manual.py +46 -0
- package/scripts/fc_curves.py +359 -0
- package/scripts/fix-fan-and-timers.cmd +39 -0
- package/scripts/fix_admin_all.py +94 -0
- package/scripts/flows.mjs +224 -0
- package/scripts/gateway.cmd +126 -0
- package/scripts/gen-image.py +420 -0
- package/scripts/gen-video.py +186 -0
- package/scripts/git-askpass.cmd +2 -2
- package/scripts/gpu-mode.py +195 -0
- package/scripts/hw-profile.py +175 -0
- package/scripts/install-schedule.cmd +37 -0
- package/scripts/install-watch.cmd +29 -0
- package/scripts/matte-cutout.py +106 -0
- package/scripts/media-enhance.py +402 -0
- package/scripts/memory-audit.py +581 -0
- package/scripts/migrate-scope.mjs +140 -139
- package/scripts/model-registry.py +519 -0
- package/scripts/openid-audit.mjs +219 -0
- package/scripts/pull-gguf.py +127 -0
- package/scripts/purge-standby.py +151 -0
- package/scripts/qq-connect-login.py +133 -0
- package/scripts/qq-ip-sync-hidden.vbs +5 -0
- package/scripts/qq-ip-sync.py +300 -0
- package/scripts/qq-login-once.cmd +20 -0
- package/scripts/qq-login-qr.py +72 -0
- package/scripts/qq-whitelist-fix.cmd +27 -0
- package/scripts/qq-whitelist-login.cmd +26 -0
- package/scripts/qq-whitelist.cmd +12 -0
- package/scripts/qq-whitelist.py +1452 -0
- package/scripts/quality-compare.py +134 -0
- package/scripts/release-all.mjs +636 -430
- package/scripts/release-check.mjs +244 -226
- package/scripts/resume-coder.cmd +38 -0
- package/scripts/secure-room/index.html +334 -0
- package/scripts/secure-room/server.py +582 -0
- package/scripts/security-check.mjs +164 -0
- package/scripts/selftest-local-llm.mjs +20 -0
- package/scripts/selftest-local-models.mjs +754 -0
- package/scripts/selftest-rotate-style.mjs +308 -0
- package/scripts/shutdown-s5-optional.cmd +21 -0
- package/scripts/sleep-2325.cmd +75 -0
- package/scripts/start-comfyui.cmd +5 -0
- package/scripts/start-strata.cmd +17 -0
- package/scripts/start-strata.vbs +11 -0
- package/scripts/start-watch-hidden.vbs +3 -0
- package/scripts/stickers/auto-tag.mjs +161 -0
- package/scripts/storage.mjs +236 -0
- package/scripts/sync-plugin-copies.mjs +98 -23
- package/scripts/tests/test-qq-whitelist.py +192 -0
- package/scripts/train/__pycache__/train-lora.cpython-311.pyc +0 -0
- package/scripts/train/gguf-quantize.py +92 -0
- package/scripts/train/gguf-to-hf.py +112 -0
- package/scripts/train/merge-lora.py +51 -0
- package/scripts/train/probe-mirrors.sh +12 -0
- package/scripts/train/probe-mirrors2.sh +20 -0
- package/scripts/train/setup-wsl.sh +23 -0
- package/scripts/train/setup-wsl2.sh +25 -0
- package/scripts/train/setup-wsl3.sh +22 -0
- package/scripts/train/setup-wsl4.sh +22 -0
- package/scripts/train/train-lora.py +319 -0
- package/scripts/vram-free.py +104 -0
- package/scripts/wechat-full-pull.mjs +1 -1
- package/settings-host.js +1047 -12
|
@@ -0,0 +1,607 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""ai-toolkit.py —— 本地 AI 能力的统一入口(CLI + HTTP),给 qqbot / dsh / workbuddy 调。
|
|
3
|
+
|
|
4
|
+
为什么要有它:
|
|
5
|
+
以前每个能力散在 gen-image.py / gen-video.py / ollama / gateway 里,调用方各写一套,
|
|
6
|
+
换个人用就出错。这里收敛成**一个稳定契约**:
|
|
7
|
+
· CLI:`python ai-toolkit.py <子命令> ... --json` 永远只打一行 JSON
|
|
8
|
+
· HTTP:`python ai-toolkit.py serve --port 8195`,POST /image /video /text,GET /health
|
|
9
|
+
· 退出码:0 成功;2 参数错;3 后端没起来;4 执行失败
|
|
10
|
+
· 失败 JSON:{"ok": false, "code": 3, "error": "...", "hint": "..."}
|
|
11
|
+
|
|
12
|
+
子命令:
|
|
13
|
+
health 各后端健康 + GPU/风扇档位 + 已装模型
|
|
14
|
+
models [--kind llm|image|...] 统一模型注册表(.models 全量扫描,含放哪的说明)
|
|
15
|
+
image -p "提示词" [--model krea|dev8|dev|schnell] [--w 1216 --h 832] [--no-enhance]
|
|
16
|
+
video -p "提示词" [--frames 49 --w 704 --h 480] [--no-enhance]
|
|
17
|
+
text -p "问题" [--model qwen3-vl:8b] [--system "..."]
|
|
18
|
+
enhance -i <图/视频/音频> [--kind image|video|audio] [--preset light|photo|anime] [--scale N]
|
|
19
|
+
episode [--story builtin|<json>] [--only images,enhance,tts,clips,final] [--with-video]
|
|
20
|
+
serve [--port 8195] 起 HTTP 服务(只监听 127.0.0.1;GET /health /models,
|
|
21
|
+
POST /image /video /text /enhance /episode)
|
|
22
|
+
|
|
23
|
+
出图/出片默认带「修复」环节(media-enhance.py):image 用 light 预设(只压噪点、不改尺寸),
|
|
24
|
+
video 做时域去噪 + 锐化 + 响度归一。要原始产物加 --no-enhance。
|
|
25
|
+
|
|
26
|
+
环境变量: COMFY_URL=http://127.0.0.1:8191 OLLAMA_URL=http://127.0.0.1:11434
|
|
27
|
+
"""
|
|
28
|
+
import argparse
|
|
29
|
+
import json
|
|
30
|
+
import os
|
|
31
|
+
import subprocess
|
|
32
|
+
import sys
|
|
33
|
+
import time
|
|
34
|
+
import urllib.request
|
|
35
|
+
|
|
36
|
+
def _resolve_root():
|
|
37
|
+
"""仓库根 = 真正有 .models 的那一层。
|
|
38
|
+
|
|
39
|
+
2026-11-29:插件被复制到 DSH 的 pnpm 副本后,本脚本位于副本里,
|
|
40
|
+
按脚本位置上溯会得到副本目录(没有 .models)→ 出图找不到权重、注册表全是空。
|
|
41
|
+
和 scripts/model-registry.py 用同一套判据:环境变量 > 逐级向上找 .models > 脚本位置。
|
|
42
|
+
"""
|
|
43
|
+
here = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
44
|
+
cands = []
|
|
45
|
+
for k in ("QQBOT_ROOT", "QQBOT_REPO_ROOT"):
|
|
46
|
+
v = (os.environ.get(k) or "").strip()
|
|
47
|
+
if v:
|
|
48
|
+
cands.append(os.path.abspath(v))
|
|
49
|
+
d = here
|
|
50
|
+
for _ in range(8):
|
|
51
|
+
cands.append(d)
|
|
52
|
+
nd = os.path.dirname(d)
|
|
53
|
+
if nd == d:
|
|
54
|
+
break
|
|
55
|
+
d = nd
|
|
56
|
+
for c in cands:
|
|
57
|
+
try:
|
|
58
|
+
if os.path.isdir(os.path.join(c, ".models")):
|
|
59
|
+
return c
|
|
60
|
+
except Exception:
|
|
61
|
+
continue
|
|
62
|
+
return here
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
ROOT = _resolve_root()
|
|
66
|
+
SCRIPTS = os.path.join(ROOT, "scripts")
|
|
67
|
+
PY = sys.executable
|
|
68
|
+
COMFY = os.environ.get("COMFY_URL", "http://127.0.0.1:8191")
|
|
69
|
+
OLLAMA = os.environ.get("OLLAMA_URL", "http://127.0.0.1:11434")
|
|
70
|
+
GATEWAY = os.environ.get("GATEWAY_URL", "http://127.0.0.1:8090")
|
|
71
|
+
CREATE_NO_WINDOW = 0x08000000
|
|
72
|
+
DETACHED_PROCESS = 0x00000008
|
|
73
|
+
DEFAULT_TEXT_MODEL = "qwen3-vl:8b"
|
|
74
|
+
|
|
75
|
+
EXIT_OK, EXIT_ARG, EXIT_DOWN, EXIT_FAIL = 0, 2, 3, 4
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class ToolError(Exception):
|
|
79
|
+
def __init__(self, code, error, hint=""):
|
|
80
|
+
super().__init__(error)
|
|
81
|
+
self.code, self.error, self.hint = code, error, hint
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def http_json(url, data=None, timeout=30, headers=None):
|
|
85
|
+
body = None if data is None else json.dumps(data).encode("utf-8")
|
|
86
|
+
h = {"Content-Type": "application/json"} if body else {}
|
|
87
|
+
h.update(headers or {})
|
|
88
|
+
req = urllib.request.Request(url, data=body, headers=h)
|
|
89
|
+
with urllib.request.urlopen(req, timeout=timeout) as r:
|
|
90
|
+
return json.loads(r.read().decode("utf-8", "replace"))
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def probe(url, timeout=3.0):
|
|
94
|
+
try:
|
|
95
|
+
urllib.request.urlopen(url, timeout=timeout).close()
|
|
96
|
+
return True
|
|
97
|
+
except Exception:
|
|
98
|
+
return False
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def gpu():
|
|
102
|
+
try:
|
|
103
|
+
out = subprocess.run(
|
|
104
|
+
["nvidia-smi", "--query-gpu=temperature.gpu,fan.speed,power.draw,memory.used,memory.total",
|
|
105
|
+
"--format=csv,noheader,nounits"],
|
|
106
|
+
capture_output=True, text=True, timeout=15, creationflags=CREATE_NO_WINDOW)
|
|
107
|
+
t, f, p, mu, mt = [x.strip() for x in out.stdout.strip().split(",")]
|
|
108
|
+
return {"temp_c": int(float(t)), "fan_pct": int(float(f)), "power_w": float(p),
|
|
109
|
+
"vram_mib": int(float(mu)), "vram_total_mib": int(float(mt))}
|
|
110
|
+
except Exception:
|
|
111
|
+
return None
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def fan_profile():
|
|
115
|
+
try:
|
|
116
|
+
with open(os.path.join(ROOT, "config", "fan", "state.json"), "r", encoding="utf-8") as f:
|
|
117
|
+
return json.load(f)
|
|
118
|
+
except Exception:
|
|
119
|
+
return None
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def installed_models():
|
|
123
|
+
want = ("flux1-schnell-Q6_K.gguf", "flux1-dev-Q4_K_S.gguf", "flux1-dev-Q8_0.gguf",
|
|
124
|
+
"flux1-krea-dev-Q8_0.gguf", "t5-v1_1-xxl-encoder-Q5_K_M.gguf",
|
|
125
|
+
"t5-v1_1-xxl-encoder-Q8_0.gguf")
|
|
126
|
+
out = {}
|
|
127
|
+
for name in want:
|
|
128
|
+
for d in ("flux-dev-gguf", "flux-schnell-gguf"):
|
|
129
|
+
p = os.path.join(ROOT, ".models", d, name)
|
|
130
|
+
if os.path.exists(p):
|
|
131
|
+
out[name] = round(os.path.getsize(p) / (1024 ** 3), 2)
|
|
132
|
+
break
|
|
133
|
+
# Qwen-Image-2512 三件套(统一目录 image/{unet,text_encoders,vae})
|
|
134
|
+
for sub, name in (("unet", "qwen-image-2512-Q4_K_M.gguf"),
|
|
135
|
+
("text_encoders", "qwen_2.5_vl_7b_fp8_scaled.safetensors"),
|
|
136
|
+
("vae", "qwen_image_vae.safetensors")):
|
|
137
|
+
p = os.path.join(ROOT, ".models", "image", sub, name)
|
|
138
|
+
if os.path.exists(p):
|
|
139
|
+
out[name] = round(os.path.getsize(p) / (1024 ** 3), 2)
|
|
140
|
+
return out
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def ollama_models():
|
|
144
|
+
try:
|
|
145
|
+
tags = http_json(OLLAMA + "/api/tags", timeout=5).get("models") or []
|
|
146
|
+
return [m.get("name") for m in tags]
|
|
147
|
+
except Exception:
|
|
148
|
+
return []
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def registry(kind=""):
|
|
152
|
+
"""统一模型注册表(scripts/model-registry.py 是唯一扫描器,这里只转调)。
|
|
153
|
+
|
|
154
|
+
文件名带连字符、不是合法模块名,所以用 spec_from_file_location 现场加载,
|
|
155
|
+
避免再抄一份扫描逻辑(两处不一致就是"面板里选不到"的根源)。
|
|
156
|
+
"""
|
|
157
|
+
import importlib.util
|
|
158
|
+
path = os.path.join(SCRIPTS, "model-registry.py")
|
|
159
|
+
if not os.path.exists(path):
|
|
160
|
+
raise ToolError(EXIT_FAIL, "注册表脚本不存在: %s" % path)
|
|
161
|
+
try:
|
|
162
|
+
spec = importlib.util.spec_from_file_location("qqbot_model_registry", path)
|
|
163
|
+
mod = importlib.util.module_from_spec(spec)
|
|
164
|
+
spec.loader.exec_module(mod)
|
|
165
|
+
return mod.payload(kind=kind or None)
|
|
166
|
+
except Exception as e:
|
|
167
|
+
raise ToolError(EXIT_FAIL, "注册表扫描失败: %s: %s" % (type(e).__name__, e),
|
|
168
|
+
"手动跑: python scripts/model-registry.py --json")
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def cmd_models(a):
|
|
172
|
+
kind = getattr(a, "kind", "") or ""
|
|
173
|
+
# 缓存永远写**全量**:按 kind 过滤只影响本次返回,否则下一个调 llm 的人会拿到一份只有图模型的缓存
|
|
174
|
+
full = registry("")
|
|
175
|
+
data = full
|
|
176
|
+
if kind:
|
|
177
|
+
ms = [m for m in full.get("models", []) if m.get("kind") == kind]
|
|
178
|
+
counts = {}
|
|
179
|
+
for m in ms:
|
|
180
|
+
counts[m["kind"]] = counts.get(m["kind"], 0) + 1
|
|
181
|
+
data = dict(full, models=ms, counts=counts,
|
|
182
|
+
total_gb=round(sum((m.get("size_gb") or 0) for m in ms), 2))
|
|
183
|
+
try:
|
|
184
|
+
os.makedirs(os.path.join(ROOT, "config"), exist_ok=True)
|
|
185
|
+
with open(os.path.join(ROOT, "config", "models.registry.json"), "w", encoding="utf-8") as f:
|
|
186
|
+
json.dump(full, f, ensure_ascii=False, indent=1)
|
|
187
|
+
data["cache"] = os.path.join(ROOT, "config", "models.registry.json").replace("\\", "/")
|
|
188
|
+
except Exception as e:
|
|
189
|
+
data = dict(data, cache_error="%s: %s" % (type(e).__name__, e))
|
|
190
|
+
return data
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _run_py(script, args, timeout, start_hint):
|
|
195
|
+
path = os.path.join(SCRIPTS, script)
|
|
196
|
+
if not os.path.exists(path):
|
|
197
|
+
raise ToolError(EXIT_FAIL, "脚本不存在: %s" % path)
|
|
198
|
+
t0 = time.time()
|
|
199
|
+
p = subprocess.run([PY, "-u", path] + args, capture_output=True, text=True,
|
|
200
|
+
timeout=timeout, creationflags=CREATE_NO_WINDOW)
|
|
201
|
+
tail = [x for x in (p.stdout or "").strip().splitlines() if x.strip()]
|
|
202
|
+
for line in reversed(tail):
|
|
203
|
+
if line.startswith("{"):
|
|
204
|
+
try:
|
|
205
|
+
data = json.loads(line)
|
|
206
|
+
data.setdefault("seconds_total", round(time.time() - t0, 1))
|
|
207
|
+
return data
|
|
208
|
+
except json.JSONDecodeError:
|
|
209
|
+
continue
|
|
210
|
+
raise ToolError(EXIT_FAIL, "%s 失败 rc=%d: %s" % (script, p.returncode,
|
|
211
|
+
(p.stderr or "")[-400:] or tail[-1:] or "无输出"),
|
|
212
|
+
start_hint)
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def _spawn_comfy():
|
|
216
|
+
"""直接 detached 拉起 ComfyUI(run_comfy.py 自己写日志)。
|
|
217
|
+
|
|
218
|
+
不用 WMI/wscript:在沙箱或非交互会话下 WMI 虽然返回 rc=0,但 wscript 转手拉起的
|
|
219
|
+
python 经常活不下来(空等 180s)。Popen + DETACHED_PROCESS 更直接,qqbot 重启也不会带走它。
|
|
220
|
+
只用 DETACHED_PROCESS 即可,不要叠加 CREATE_NO_WINDOW(两者语义冲突,容易出怪问题)。
|
|
221
|
+
"""
|
|
222
|
+
pf = os.path.join(ROOT, "services", "comfyui", "run_comfy.py")
|
|
223
|
+
if not os.path.exists(pf):
|
|
224
|
+
raise ToolError(EXIT_FAIL, "找不到 %s" % pf, "重新拉一份 ComfyUI 或改 services/comfyui 路径")
|
|
225
|
+
subprocess.Popen([PY, pf], creationflags=DETACHED_PROCESS,
|
|
226
|
+
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
|
227
|
+
close_fds=True)
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def ensure_comfy(start=False):
|
|
231
|
+
if probe(COMFY + "/system_stats"):
|
|
232
|
+
return
|
|
233
|
+
if start:
|
|
234
|
+
_spawn_comfy()
|
|
235
|
+
t0 = time.time()
|
|
236
|
+
while time.time() - t0 < 180:
|
|
237
|
+
time.sleep(3)
|
|
238
|
+
if probe(COMFY + "/system_stats"):
|
|
239
|
+
return
|
|
240
|
+
raise ToolError(EXIT_DOWN, "ComfyUI 未响应 %s" % COMFY,
|
|
241
|
+
"看 F:\\qqbot\\logs\\comfyui8191.log;或手动跑 services\\comfyui\\start_comfyui_8191.bat")
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def cmd_health(a):
|
|
245
|
+
g = gpu()
|
|
246
|
+
fan = fan_profile()
|
|
247
|
+
if fan and g and fan.get("gpu_fan") is not None:
|
|
248
|
+
# 风扇档位有可能被外部(FanControl 自己加载日常配置)改回去,状态文件就会骗人
|
|
249
|
+
if abs(int(g["fan_pct"]) - int(fan["gpu_fan"])) > 8:
|
|
250
|
+
fan = dict(fan, stale=True,
|
|
251
|
+
note="状态文件写 %s%%,实际 %s%%(档位可能被外部改回去了)"
|
|
252
|
+
% (fan.get("gpu_fan"), g["fan_pct"]))
|
|
253
|
+
return {
|
|
254
|
+
"ok": True,
|
|
255
|
+
"comfyui": probe(COMFY + "/system_stats"),
|
|
256
|
+
"ollama": probe(OLLAMA + "/api/tags"),
|
|
257
|
+
"gateway": probe(GATEWAY + "/healthz"),
|
|
258
|
+
"gpu": g,
|
|
259
|
+
"fan": fan,
|
|
260
|
+
"models": installed_models(),
|
|
261
|
+
"text_models": ollama_models(),
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def restore_fan(timeout=30):
|
|
266
|
+
"""出图后把风扇切回日常档 —— 只在**显式开过** QQBOT_FAN_TASK 时才做。
|
|
267
|
+
|
|
268
|
+
2026-12-02:主人明确说不要替他动风扇(空转很吵,且 FanControl 的进出风曲线本身有问题),
|
|
269
|
+
所以默认完全不动:既不改档位,也不写 state.json。
|
|
270
|
+
"""
|
|
271
|
+
if (os.environ.get("QQBOT_FAN_TASK", "") or "").strip().lower() not in ("1", "true", "yes", "on"):
|
|
272
|
+
return
|
|
273
|
+
script = os.path.join(SCRIPTS, "fan-mode.py")
|
|
274
|
+
if not os.path.exists(script):
|
|
275
|
+
return
|
|
276
|
+
try:
|
|
277
|
+
subprocess.run([PY, script, "--daily"], timeout=timeout,
|
|
278
|
+
creationflags=CREATE_NO_WINDOW,
|
|
279
|
+
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
|
280
|
+
except Exception:
|
|
281
|
+
pass
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def cmd_image(a):
|
|
285
|
+
ensure_comfy(a.start)
|
|
286
|
+
args = ["-p", a.prompt, "--model", a.model, "--json", "--no-cool"]
|
|
287
|
+
if a.w:
|
|
288
|
+
args += ["--w", str(a.w)]
|
|
289
|
+
if a.h:
|
|
290
|
+
args += ["--h", str(a.h)]
|
|
291
|
+
if a.steps:
|
|
292
|
+
args += ["--steps", str(a.steps)]
|
|
293
|
+
if a.seed >= 0:
|
|
294
|
+
args += ["--seed", str(a.seed)]
|
|
295
|
+
if a.out:
|
|
296
|
+
args += ["-o", a.out]
|
|
297
|
+
neg = getattr(a, "negative", "") or ""
|
|
298
|
+
if neg:
|
|
299
|
+
args += ["-n", neg]
|
|
300
|
+
if float(getattr(a, "cfg", 0) or 0) > 0:
|
|
301
|
+
args += ["--cfg", str(float(a.cfg))]
|
|
302
|
+
if float(getattr(a, "guidance", 0) or 0) > 0:
|
|
303
|
+
args += ["--guidance", str(float(a.guidance))]
|
|
304
|
+
if getattr(a, "init", ""):
|
|
305
|
+
args += ["--init", a.init, "--denoise", str(getattr(a, "denoise", 0.55) or 0.55)]
|
|
306
|
+
try:
|
|
307
|
+
data = _run_py("gen-image.py", args, a.timeout, "看 F:\\qqbot\\logs\\comfyui8191.log")
|
|
308
|
+
finally:
|
|
309
|
+
if not a.no_cool:
|
|
310
|
+
restore_fan()
|
|
311
|
+
if getattr(a, "enhance", False):
|
|
312
|
+
data = _enhance_image_result(data, getattr(a, "enhance_preset", "") or "light", 1)
|
|
313
|
+
return data
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def _enhance_image_result(data, preset="light", scale=1):
|
|
317
|
+
"""出图后的修复环节:把 files 换成增强后的那张,原图留在 raw_files 里可追溯。"""
|
|
318
|
+
files = data.get("files") or []
|
|
319
|
+
if not files:
|
|
320
|
+
return data
|
|
321
|
+
raw = files[0]
|
|
322
|
+
try:
|
|
323
|
+
rep = _run_py("media-enhance.py", ["image", "-i", raw, "--preset", preset,
|
|
324
|
+
"--scale", str(scale), "--json"],
|
|
325
|
+
900, "看 out/image/<月>/enhanced/ 下的 -report.json")
|
|
326
|
+
except ToolError as e:
|
|
327
|
+
# 增强失败不能让「图已经出好了」这件事变成失败,只标注
|
|
328
|
+
return dict(data, enhance={"ok": False, "code": e.code, "error": e.error})
|
|
329
|
+
if not rep.get("ok"):
|
|
330
|
+
return dict(data, enhance={"ok": False, "error": rep.get("error")})
|
|
331
|
+
out = dict(data)
|
|
332
|
+
out.update({"files": [rep["output"]], "raw_files": [raw], "enhance": {
|
|
333
|
+
"preset": preset, "scale": rep.get("scale"), "compare": rep.get("compare"),
|
|
334
|
+
"gain": rep.get("gain"), "before": rep.get("before"), "after": rep.get("after"),
|
|
335
|
+
"report": rep.get("report")}})
|
|
336
|
+
return out
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
def cmd_video(a):
|
|
340
|
+
ensure_comfy(a.start)
|
|
341
|
+
# 风扇:默认不碰(空转很吵)。要提转速自己先跑 fan-mode.py --task。
|
|
342
|
+
args = ["-p", a.prompt, "--json"]
|
|
343
|
+
if a.out:
|
|
344
|
+
args += ["-o", a.out]
|
|
345
|
+
for k in ("w", "h", "frames", "steps"):
|
|
346
|
+
v = getattr(a, k, 0)
|
|
347
|
+
if v:
|
|
348
|
+
args += ["--" + k, str(v)]
|
|
349
|
+
if getattr(a, "seed", -1) is not None and getattr(a, "seed", -1) >= 0:
|
|
350
|
+
args += ["--seed", str(a.seed)]
|
|
351
|
+
data = _run_py("gen-video.py", args, a.timeout, "Wan2.2 5B 很吃显存,先把 Ollama 模型卸载")
|
|
352
|
+
if getattr(a, "enhance", False) and data.get("file"):
|
|
353
|
+
try:
|
|
354
|
+
rep = _run_py("media-enhance.py", ["video", "-i", data["file"], "--json"],
|
|
355
|
+
a.timeout, "看 out/video/<月>/enhanced/ 下的 -report.json")
|
|
356
|
+
if rep.get("ok"):
|
|
357
|
+
data = dict(data, raw_file=data["file"], file=rep["output"],
|
|
358
|
+
files=[rep["output"]], enhance={
|
|
359
|
+
"loudness_before": rep.get("loudness_before"),
|
|
360
|
+
"loudness_after": rep.get("loudness_after"),
|
|
361
|
+
"before": rep.get("before"), "after": rep.get("after"),
|
|
362
|
+
"report": rep.get("report")})
|
|
363
|
+
except ToolError as e:
|
|
364
|
+
data = dict(data, enhance={"ok": False, "code": e.code, "error": e.error})
|
|
365
|
+
return data
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
def cmd_enhance(a):
|
|
369
|
+
"""显式修复入口:image / video / audio 三种输入统一走 media-enhance.py。"""
|
|
370
|
+
args = [a.kind, "-i", a.input, "--json"]
|
|
371
|
+
if a.kind == "image":
|
|
372
|
+
if a.preset:
|
|
373
|
+
args += ["--preset", a.preset]
|
|
374
|
+
if a.scale:
|
|
375
|
+
args += ["--scale", str(a.scale)]
|
|
376
|
+
elif a.kind == "video" and a.scale:
|
|
377
|
+
args += ["--scale", str(a.scale)]
|
|
378
|
+
if not os.path.exists(a.input):
|
|
379
|
+
raise ToolError(EXIT_ARG, "输入不存在: %s" % a.input)
|
|
380
|
+
return _run_py("media-enhance.py", args, a.timeout, "看 media-enhance.py 的 --help")
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
def cmd_episode(a):
|
|
384
|
+
"""30 秒级短片流水线(分镜 → 出图 → 修复 → 配音 → 拼片),全部确定性。"""
|
|
385
|
+
args = ["--story", a.story, "--only", a.only, "--json"]
|
|
386
|
+
if a.force:
|
|
387
|
+
args += ["--force", a.force]
|
|
388
|
+
if a.with_video:
|
|
389
|
+
args += ["--with-video", "--video-shot", a.video_shot]
|
|
390
|
+
return _run_py("episode.py", args, a.timeout, "python scripts/episode.py --list 看分镜表")
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
def cmd_text(a):
|
|
394
|
+
if not probe(OLLAMA + "/api/tags"):
|
|
395
|
+
raise ToolError(EXIT_DOWN, "Ollama 未响应 %s" % OLLAMA, "启动 Ollama 或改用 gateway")
|
|
396
|
+
msgs = []
|
|
397
|
+
if a.system:
|
|
398
|
+
msgs.append({"role": "system", "content": a.system})
|
|
399
|
+
msgs.append({"role": "user", "content": a.prompt})
|
|
400
|
+
data = http_json(OLLAMA + "/api/chat",
|
|
401
|
+
{"model": a.model, "messages": msgs, "stream": False,
|
|
402
|
+
"options": {"temperature": a.temperature}},
|
|
403
|
+
timeout=a.timeout)
|
|
404
|
+
return {"ok": True, "model": a.model, "text": (data.get("message") or {}).get("content", "")}
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
def cmd_serve(a):
|
|
408
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
409
|
+
|
|
410
|
+
class Handler(BaseHTTPRequestHandler):
|
|
411
|
+
server_version = "ai-toolkit/1.0"
|
|
412
|
+
|
|
413
|
+
def _send(self, code, obj):
|
|
414
|
+
raw = json.dumps(obj, ensure_ascii=False).encode("utf-8")
|
|
415
|
+
self.send_response(code)
|
|
416
|
+
self.send_header("Content-Type", "application/json; charset=utf-8")
|
|
417
|
+
self.send_header("Content-Length", str(len(raw)))
|
|
418
|
+
self.end_headers()
|
|
419
|
+
self.wfile.write(raw)
|
|
420
|
+
|
|
421
|
+
def log_message(self, fmt, *args):
|
|
422
|
+
sys.stderr.write("%s %s\n" % (time.strftime("%H:%M:%S"), fmt % args))
|
|
423
|
+
|
|
424
|
+
def do_GET(self):
|
|
425
|
+
if self.path.startswith("/health"):
|
|
426
|
+
self._send(200, cmd_health(argparse.Namespace()))
|
|
427
|
+
elif self.path.startswith("/models"):
|
|
428
|
+
try:
|
|
429
|
+
q = ""
|
|
430
|
+
if "?" in self.path:
|
|
431
|
+
for kv in self.path.split("?", 1)[1].split("&"):
|
|
432
|
+
if kv.startswith("kind="):
|
|
433
|
+
q = kv[5:]
|
|
434
|
+
self._send(200, cmd_models(argparse.Namespace(kind=q)))
|
|
435
|
+
except ToolError as e:
|
|
436
|
+
self._send(200, {"ok": False, "code": e.code, "error": e.error, "hint": e.hint})
|
|
437
|
+
except Exception as e:
|
|
438
|
+
self._send(200, {"ok": False, "code": EXIT_FAIL,
|
|
439
|
+
"error": "%s: %s" % (type(e).__name__, e)})
|
|
440
|
+
else:
|
|
441
|
+
self._send(404, {"ok": False, "code": 404, "error": "no such path"})
|
|
442
|
+
|
|
443
|
+
def do_POST(self):
|
|
444
|
+
try:
|
|
445
|
+
n = int(self.headers.get("Content-Length") or 0)
|
|
446
|
+
body = json.loads(self.rfile.read(n).decode("utf-8") or "{}")
|
|
447
|
+
except Exception as e:
|
|
448
|
+
self._send(400, {"ok": False, "code": EXIT_ARG, "error": "bad json: %s" % e})
|
|
449
|
+
return
|
|
450
|
+
try:
|
|
451
|
+
if self.path.startswith("/image"):
|
|
452
|
+
ns = argparse.Namespace(prompt=body.get("prompt", ""), model=body.get("model", "krea"),
|
|
453
|
+
w=int(body.get("width") or 0), h=int(body.get("height") or 0),
|
|
454
|
+
steps=int(body.get("steps") or 0), seed=int(body.get("seed", -1)),
|
|
455
|
+
negative=body.get("negative", "") or "",
|
|
456
|
+
cfg=float(body.get("cfg") or 0),
|
|
457
|
+
guidance=float(body.get("guidance") or 0),
|
|
458
|
+
out=body.get("out", ""), no_cool=bool(body.get("no_cool")),
|
|
459
|
+
enhance=bool(body.get("enhance", True)),
|
|
460
|
+
enhance_preset=body.get("enhance_preset", "light"),
|
|
461
|
+
start=bool(body.get("start")),
|
|
462
|
+
timeout=int(body.get("timeout") or 900))
|
|
463
|
+
self._send(200, cmd_image(ns))
|
|
464
|
+
elif self.path.startswith("/video"):
|
|
465
|
+
ns = argparse.Namespace(prompt=body.get("prompt", ""), out=body.get("out", ""),
|
|
466
|
+
w=int(body.get("width") or 0), h=int(body.get("height") or 0),
|
|
467
|
+
frames=int(body.get("frames") or 0),
|
|
468
|
+
steps=int(body.get("steps") or 0),
|
|
469
|
+
seed=int(body.get("seed", -1)),
|
|
470
|
+
enhance=bool(body.get("enhance", True)),
|
|
471
|
+
start=bool(body.get("start")),
|
|
472
|
+
timeout=int(body.get("timeout") or 1800))
|
|
473
|
+
self._send(200, cmd_video(ns))
|
|
474
|
+
elif self.path.startswith("/enhance"):
|
|
475
|
+
ns = argparse.Namespace(kind=body.get("kind", "image"), input=body.get("input", ""),
|
|
476
|
+
preset=body.get("preset", ""), scale=int(body.get("scale") or 0),
|
|
477
|
+
timeout=int(body.get("timeout") or 1800))
|
|
478
|
+
self._send(200, cmd_enhance(ns))
|
|
479
|
+
elif self.path.startswith("/episode"):
|
|
480
|
+
ns = argparse.Namespace(story=body.get("story", "builtin"),
|
|
481
|
+
only=body.get("only", "all"), force=body.get("force", ""),
|
|
482
|
+
with_video=bool(body.get("with_video")),
|
|
483
|
+
video_shot=body.get("video_shot", "04"),
|
|
484
|
+
keep_fan=bool(body.get("keep_fan")),
|
|
485
|
+
timeout=int(body.get("timeout") or 3600))
|
|
486
|
+
self._send(200, cmd_episode(ns))
|
|
487
|
+
elif self.path.startswith("/text"):
|
|
488
|
+
ns = argparse.Namespace(prompt=body.get("prompt", ""), model=body.get("model") or DEFAULT_TEXT_MODEL,
|
|
489
|
+
system=body.get("system", ""),
|
|
490
|
+
temperature=float(body.get("temperature", 0.7)),
|
|
491
|
+
timeout=int(body.get("timeout") or 300))
|
|
492
|
+
self._send(200, cmd_text(ns))
|
|
493
|
+
else:
|
|
494
|
+
self._send(404, {"ok": False, "code": 404, "error": "no such path"})
|
|
495
|
+
except ToolError as e:
|
|
496
|
+
self._send(200, {"ok": False, "code": e.code, "error": e.error, "hint": e.hint})
|
|
497
|
+
except Exception as e:
|
|
498
|
+
self._send(200, {"ok": False, "code": EXIT_FAIL, "error": "%s: %s" % (type(e).__name__, e)})
|
|
499
|
+
|
|
500
|
+
srv = ThreadingHTTPServer((a.host, a.port), Handler)
|
|
501
|
+
print(json.dumps({"ok": True, "listen": "http://%s:%d" % (a.host, a.port),
|
|
502
|
+
"routes": ["GET /health", "GET /models", "POST /image", "POST /video",
|
|
503
|
+
"POST /text", "POST /enhance", "POST /episode"]},
|
|
504
|
+
ensure_ascii=False), flush=True)
|
|
505
|
+
srv.serve_forever()
|
|
506
|
+
|
|
507
|
+
|
|
508
|
+
def build_parser():
|
|
509
|
+
ap = argparse.ArgumentParser(description="本地 AI 工具箱(CLI + HTTP)")
|
|
510
|
+
ap.add_argument("--json", action="store_true", help="只输出一行 JSON(agent 用)")
|
|
511
|
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
512
|
+
|
|
513
|
+
sub.add_parser("health")
|
|
514
|
+
|
|
515
|
+
pm = sub.add_parser("models")
|
|
516
|
+
pm.add_argument("--kind", default="", help="只列某一类: llm/image/video/audio/ocr")
|
|
517
|
+
|
|
518
|
+
pi = sub.add_parser("image")
|
|
519
|
+
pi.add_argument("-p", "--prompt", required=True)
|
|
520
|
+
pi.add_argument("--model", default="krea",
|
|
521
|
+
choices=["schnell", "dev", "dev8", "krea", "qwen"])
|
|
522
|
+
pi.add_argument("--w", type=int, default=0)
|
|
523
|
+
pi.add_argument("--h", type=int, default=0)
|
|
524
|
+
pi.add_argument("--steps", type=int, default=0)
|
|
525
|
+
pi.add_argument("--seed", type=int, default=-1)
|
|
526
|
+
pi.add_argument("-o", "--out", default="")
|
|
527
|
+
pi.add_argument("--init", default="", help="img2img 底图(本机图片路径),用来保持角色/姿势只换衣服或加细节")
|
|
528
|
+
pi.add_argument("--denoise", type=float, default=0.55, help="img2img 改动幅度 0.35~0.8")
|
|
529
|
+
pi.add_argument("--enhance", dest="enhance", action="store_true", default=True,
|
|
530
|
+
help="出图后自动修复(去噪/局部对比/锐化),默认开")
|
|
531
|
+
pi.add_argument("--no-enhance", dest="enhance", action="store_false", help="关掉自动修复,只要原始出图")
|
|
532
|
+
pi.add_argument("--enhance-preset", default="light", choices=["light", "photo", "anime"],
|
|
533
|
+
help="修复预设:light=不改尺寸只压噪点(默认);photo/anime 是 2x 放大档")
|
|
534
|
+
pi.add_argument("--start", action="store_true", help="ComfyUI 没起就先拉起来")
|
|
535
|
+
pi.add_argument("--no-cool", action="store_true")
|
|
536
|
+
pi.add_argument("--timeout", type=int, default=900)
|
|
537
|
+
|
|
538
|
+
pv = sub.add_parser("video")
|
|
539
|
+
pv.add_argument("-p", "--prompt", required=True)
|
|
540
|
+
pv.add_argument("-o", "--out", default="")
|
|
541
|
+
pv.add_argument("--w", type=int, default=0)
|
|
542
|
+
pv.add_argument("--h", type=int, default=0)
|
|
543
|
+
pv.add_argument("--frames", type=int, default=0)
|
|
544
|
+
pv.add_argument("--steps", type=int, default=0)
|
|
545
|
+
pv.add_argument("--seed", type=int, default=-1)
|
|
546
|
+
pv.add_argument("--enhance", dest="enhance", action="store_true", default=True,
|
|
547
|
+
help="出片后自动修复(时域去噪/锐化/响度归一),默认开")
|
|
548
|
+
pv.add_argument("--no-enhance", dest="enhance", action="store_false")
|
|
549
|
+
pv.add_argument("--start", action="store_true")
|
|
550
|
+
pv.add_argument("--timeout", type=int, default=1800)
|
|
551
|
+
|
|
552
|
+
pe = sub.add_parser("enhance")
|
|
553
|
+
pe.add_argument("--kind", default="image", choices=["image", "video", "audio"])
|
|
554
|
+
pe.add_argument("-i", "--input", required=True)
|
|
555
|
+
pe.add_argument("--preset", default="", choices=["", "light", "photo", "anime"])
|
|
556
|
+
pe.add_argument("--scale", type=int, default=0)
|
|
557
|
+
pe.add_argument("--timeout", type=int, default=1800)
|
|
558
|
+
|
|
559
|
+
pep = sub.add_parser("episode")
|
|
560
|
+
pep.add_argument("--story", default="builtin")
|
|
561
|
+
pep.add_argument("--only", default="all")
|
|
562
|
+
pep.add_argument("--force", default="")
|
|
563
|
+
pep.add_argument("--with-video", action="store_true")
|
|
564
|
+
pep.add_argument("--video-shot", default="04")
|
|
565
|
+
pep.add_argument("--timeout", type=int, default=3600)
|
|
566
|
+
|
|
567
|
+
pt = sub.add_parser("text")
|
|
568
|
+
pt.add_argument("-p", "--prompt", required=True)
|
|
569
|
+
pt.add_argument("--model", default=DEFAULT_TEXT_MODEL)
|
|
570
|
+
pt.add_argument("--system", default="")
|
|
571
|
+
pt.add_argument("--temperature", type=float, default=0.7)
|
|
572
|
+
pt.add_argument("--timeout", type=int, default=300)
|
|
573
|
+
|
|
574
|
+
ps = sub.add_parser("serve")
|
|
575
|
+
ps.add_argument("--host", default="127.0.0.1")
|
|
576
|
+
ps.add_argument("--port", type=int, default=8195)
|
|
577
|
+
return ap
|
|
578
|
+
|
|
579
|
+
|
|
580
|
+
def main(argv=None):
|
|
581
|
+
# --json 允许放在任意位置(agent 习惯写在最后),先摘出来再解析
|
|
582
|
+
argv = list(sys.argv[1:] if argv is None else argv)
|
|
583
|
+
force_json = "--json" in argv
|
|
584
|
+
argv = [x for x in argv if x != "--json"]
|
|
585
|
+
a = build_parser().parse_args(argv)
|
|
586
|
+
a.json = force_json
|
|
587
|
+
handler = {"health": cmd_health, "models": cmd_models, "image": cmd_image, "video": cmd_video,
|
|
588
|
+
"text": cmd_text, "enhance": cmd_enhance, "episode": cmd_episode,
|
|
589
|
+
"serve": cmd_serve}[a.cmd]
|
|
590
|
+
try:
|
|
591
|
+
data = handler(a)
|
|
592
|
+
if a.cmd == "serve":
|
|
593
|
+
return EXIT_OK
|
|
594
|
+
print(json.dumps(data, ensure_ascii=False) if a.json else
|
|
595
|
+
json.dumps(data, ensure_ascii=False, indent=2))
|
|
596
|
+
return EXIT_OK
|
|
597
|
+
except ToolError as e:
|
|
598
|
+
print(json.dumps({"ok": False, "code": e.code, "error": e.error, "hint": e.hint},
|
|
599
|
+
ensure_ascii=False))
|
|
600
|
+
return e.code
|
|
601
|
+
except subprocess.TimeoutExpired:
|
|
602
|
+
print(json.dumps({"ok": False, "code": EXIT_FAIL, "error": "超时"}, ensure_ascii=False))
|
|
603
|
+
return EXIT_FAIL
|
|
604
|
+
|
|
605
|
+
|
|
606
|
+
if __name__ == "__main__":
|
|
607
|
+
sys.exit(main())
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""把显卡风扇从「手动 22% 被驱动曲线抽到 63%」改成稳定的固定 45%(约 2600 转)。
|
|
2
|
+
|
|
3
|
+
用法(需要管理员/提权):python apply-fan-gpu45.py
|
|
4
|
+
它会:改 userConfig.json 里 GPU 控制项 → 备份 → 重启 FanControl。
|
|
5
|
+
"""
|
|
6
|
+
import io
|
|
7
|
+
import json
|
|
8
|
+
import subprocess
|
|
9
|
+
import sys
|
|
10
|
+
import time
|
|
11
|
+
|
|
12
|
+
CFG = r"C:\Program Files (x86)\FanControl\Configurations\userConfig.json"
|
|
13
|
+
GPU_ID = "NVApiWrapper/0-TU102-A/control/0"
|
|
14
|
+
TARGET = int(sys.argv[1]) if len(sys.argv) > 1 else 45
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def main() -> int:
|
|
18
|
+
with io.open(CFG, encoding="utf-8") as f:
|
|
19
|
+
cfg = json.load(f)
|
|
20
|
+
hit = None
|
|
21
|
+
for ctl in cfg["FanControl"]["Controls"]:
|
|
22
|
+
if ctl.get("Identifier") == GPU_ID:
|
|
23
|
+
hit = ctl
|
|
24
|
+
break
|
|
25
|
+
if hit is None:
|
|
26
|
+
print("找不到显卡控制项", file=sys.stderr)
|
|
27
|
+
return 2
|
|
28
|
+
old = hit.get("ManualControlValue")
|
|
29
|
+
hit["ManualControl"] = True
|
|
30
|
+
hit["ManualControlValue"] = TARGET
|
|
31
|
+
hit["MinimumPercent"] = min(int(hit.get("MinimumPercent") or 0), TARGET)
|
|
32
|
+
bak = CFG + time.strftime(".bak-gpu45-%Y%m%d-%H%M%S")
|
|
33
|
+
with io.open(bak, "w", encoding="utf-8") as f:
|
|
34
|
+
json.dump(cfg, f, ensure_ascii=False, indent=2)
|
|
35
|
+
with io.open(CFG, "w", encoding="utf-8") as f:
|
|
36
|
+
json.dump(cfg, f, ensure_ascii=False, indent=2)
|
|
37
|
+
print(f"GPU 风扇 {old} -> {TARGET}%,备份 {bak}")
|
|
38
|
+
|
|
39
|
+
subprocess.run(["taskkill", "/IM", "FanControl.exe", "/F"], capture_output=True)
|
|
40
|
+
time.sleep(2)
|
|
41
|
+
subprocess.run([r"C:\Program Files (x86)\FanControl\FanControl.exe"],
|
|
42
|
+
cwd=r"C:\Program Files (x86)\FanControl")
|
|
43
|
+
time.sleep(6)
|
|
44
|
+
out = subprocess.run(["nvidia-smi", "--query-gpu=fan.speed,temperature.gpu,power.draw",
|
|
45
|
+
"--format=csv,noheader"], capture_output=True, text=True)
|
|
46
|
+
print("当前显卡:", out.stdout.strip())
|
|
47
|
+
return 0
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
if __name__ == "__main__":
|
|
51
|
+
sys.exit(main())
|