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,263 +1,380 @@
1
- # -*- coding: utf-8 -*-
2
- """fan-mode.py —— 用 FanControl 在「日常档 / 任务档」之间切风扇转速。
3
-
4
- 为什么这么做:
5
- FanControl 把风扇都设成了固定占空比(ManualControlValue):GPU 22%、CPU 55%、
6
- 进风 30%、出风 31%。这是"日常生活"档,跑 ComfyUI / 本地推理时 88C 也只吹 22%,
7
- 很容易过热降频。这里不改驱动、不装 Afterburner,而是生成两份 FanControl 配置
8
- 文件(daily / task),再用 FanControl 自己的命令行 `--config` 热切换:
9
- FanControl.exe --config <cfg.json> # 已运行的实例会直接吃下新配置
10
- (命令开关是从 FanControl.dll 里挖出来的:-c/--config -m/--minimized -e/--exit -w/--window)
11
-
12
- 用法:
13
- python scripts/fan-mode.py --status # 看当前风扇/温度/生效档位
14
- python scripts/fan-mode.py --make # 重新生成 daily.json / task.json
15
- python scripts/fan-mode.py --make --force # 按「当前 FanControl 里的值」重做 daily 基线
16
- python scripts/fan-mode.py --task # 切任务档(GPU 80%)
17
- python scripts/fan-mode.py --daily # 切回日常档
18
- python scripts/fan-mode.py --apply task # 同上,显式指定
19
-
20
- 被谁调用:gpu-mode.py --task/--restore、gen-image.py、ai-toolkit。
21
- """
22
- import argparse
23
- import json
24
- import os
25
- import subprocess
26
- import sys
27
- import time
28
- from datetime import datetime
29
-
30
- ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
31
- FC_EXE = r"C:\Program Files (x86)\FanControl\FanControl.exe"
32
- FC_USER_CFG = r"C:\Program Files (x86)\FanControl\Configurations\userConfig.json"
33
- CFG_DIR = os.path.join(ROOT, "config", "fan")
34
- STATE_FILE = os.path.join(CFG_DIR, "state.json")
35
- LOG_FILE = os.path.join(ROOT, "logs", "fan.log")
36
- CREATE_NO_WINDOW = 0x08000000
37
-
38
- # 每个风扇在两档下的目标占空比。daily 会被「当前 FanControl 配置」里的实际值覆盖,
39
- # 所以用户自己在 FanControl 里调过的日常值不会被这里改掉。
40
- TARGETS = [
41
- # key, 匹配方式, 匹配串, 任务档占空比
42
- ("cpu", "name", "CPU Fan", 75),
43
- ("in", "name", "进风", 60),
44
- ("out", "name", "出风", 65),
45
- ("gpu", "identifier", "NVApiWrapper", 80),
46
- ]
47
-
48
-
49
- def log(msg):
50
- line = "%s %s" % (datetime.now().strftime("%Y-%m-%d %H:%M:%S"), msg)
51
- print(line)
52
- try:
53
- os.makedirs(os.path.dirname(LOG_FILE), exist_ok=True)
54
- with open(LOG_FILE, "a", encoding="utf-8") as f:
55
- f.write(line + "\n")
56
- except OSError:
57
- pass
58
-
59
-
60
- def smi(*fields):
61
- try:
62
- out = subprocess.run(
63
- ["nvidia-smi", "--query-gpu=" + ",".join(fields), "--format=csv,noheader,nounits"],
64
- capture_output=True, text=True, timeout=15, creationflags=CREATE_NO_WINDOW)
65
- rows = (out.stdout or "").strip().splitlines()
66
- return rows[0].split(",") if rows else None
67
- except Exception:
68
- return None
69
-
70
-
71
- def _card_key(card):
72
- """返回 (key, 任务档占空比),不匹配返回 (None, None)。"""
73
- nick = (card.get("NickName") or "")
74
- ident = (card.get("Identifier") or "")
75
- for key, how, pat, task_pct in TARGETS:
76
- hay = ident if how == "identifier" else nick
77
- if pat.lower() in hay.lower():
78
- return key, task_pct
79
- return None, None
80
-
81
-
82
- def read_source_config():
83
- """以 FanControl 当前 userConfig.json 为模板(只读,不写 Program Files)。"""
84
- with open(FC_USER_CFG, "r", encoding="utf-8-sig") as f:
85
- return json.load(f)
86
-
87
-
88
- def build(force=False):
89
- """生成 daily.json(日常快照)与 task.json(任务档)。"""
90
- os.makedirs(CFG_DIR, exist_ok=True)
91
- daily_path = os.path.join(CFG_DIR, "daily.json")
92
- task_path = os.path.join(CFG_DIR, "task.json")
93
- if os.path.exists(daily_path) and not force:
94
- log("daily.json 已存在(保留用户日常快照);需要重建请加 --force")
95
- return daily_path, task_path
96
-
97
- cfg = read_source_config()
98
- daily, task = json.loads(json.dumps(cfg)), json.loads(json.dumps(cfg))
99
- seen = []
100
- for card in daily["FanControl"]["Controls"]:
101
- key, task_pct = _card_key(card)
102
- if not key:
103
- continue
104
- daily_pct = card.get("ManualControlValue", 50)
105
- card["Enable"] = True
106
- card["ManualControl"] = True
107
- seen.append((key, card.get("NickName"), daily_pct, max(task_pct, int(daily_pct))))
108
- # task 用同一套 key 覆盖
109
- for card in task["FanControl"]["Controls"]:
110
- key, task_pct = _card_key(card)
111
- if not key:
112
- continue
113
- card["Enable"] = True
114
- card["ManualControl"] = True
115
- card["ManualControlValue"] = int(task_pct)
116
-
117
- for path, data in ((daily_path, daily), (task_path, task)):
118
- tmp = path + ".tmp"
119
- with open(tmp, "w", encoding="utf-8") as f:
120
- json.dump(data, f, ensure_ascii=False, indent=2)
121
- os.replace(tmp, path)
122
- detail = ", ".join("%s %s%%->%s%%" % (k, d, t) for k, _n, d, t in seen)
123
- log("已生成配置: %s | %s" % (os.path.basename(daily_path), detail))
124
- return daily_path, task_path
125
-
126
-
127
- def fancontrol_running():
128
- try:
129
- out = subprocess.run(["tasklist", "/FI", "IMAGENAME eq FanControl.exe", "/NH"],
130
- capture_output=True, text=True, timeout=15,
131
- creationflags=CREATE_NO_WINDOW)
132
- return "FanControl.exe" in (out.stdout or "")
133
- except Exception:
134
- return False
135
-
136
-
137
- def gpu_fan():
138
- row = smi("fan.speed")
139
- if not row:
140
- return None
141
- try:
142
- return int(float(row[0].strip()))
143
- except ValueError:
144
- return None
145
-
146
-
147
- def write_state(profile, ok, note=""):
148
- os.makedirs(CFG_DIR, exist_ok=True)
149
- data = {"profile": profile if ok else "unknown", "ok": bool(ok),
150
- "gpu_fan": gpu_fan(), "note": note,
151
- "at": datetime.now().strftime("%Y-%m-%d %H:%M:%S")}
152
- tmp = STATE_FILE + ".tmp"
153
- with open(tmp, "w", encoding="utf-8") as f:
154
- json.dump(data, f, ensure_ascii=False, indent=2)
155
- os.replace(tmp, STATE_FILE)
156
- return data
157
-
158
-
159
- def expected_pct(cfg_path):
160
- """从生成好的配置里读 GPU 风扇目标占空比(用户/历史调过的值优先,不硬编码)。"""
161
- try:
162
- with open(cfg_path, "r", encoding="utf-8") as f:
163
- data = json.load(f)
164
- for card in data["FanControl"]["Controls"]:
165
- key, _task_pct = _card_key(card)
166
- if key == "gpu":
167
- return int(card.get("ManualControlValue", 0))
168
- except Exception:
169
- pass
170
- return None
171
-
172
-
173
- def apply(profile, expect_pct=None, wait=20):
174
- """切换档位:FanControl --config <cfg>,然后回读 GPU 风扇确认真生效。"""
175
- if not os.path.exists(FC_EXE):
176
- log("找不到 FanControl.exe: %s" % FC_EXE)
177
- return 3
178
- daily_path, task_path = build(force=False)
179
- cfg = task_path if profile == "task" else daily_path
180
- if not os.path.exists(cfg):
181
- log("配置缺失: %s" % cfg)
182
- return 2
183
- if expect_pct is None:
184
- expect_pct = expected_pct(cfg)
185
- if not fancontrol_running():
186
- # 没在跑就直接带配置拉起来(风扇控制需要管理员,通常由用户/开机自启启动)
187
- try:
188
- subprocess.Popen([FC_EXE, "-c", cfg, "-m"], creationflags=CREATE_NO_WINDOW)
189
- log("FanControl 未运行,已按 %s 档拉起(若风扇不生效,请以管理员身份启动 FanControl)" % profile)
190
- except Exception as e:
191
- log("拉起 FanControl 失败: %s" % e)
192
- return 3
193
- else:
194
- try:
195
- subprocess.run([FC_EXE, "-c", cfg], timeout=30, creationflags=CREATE_NO_WINDOW)
196
- except Exception as e:
197
- log("FanControl --config 失败: %s" % e)
198
- return 3
199
-
200
- want = expect_pct
201
- t0 = time.time()
202
- cur = gpu_fan()
203
- while time.time() - t0 < wait:
204
- time.sleep(2)
205
- cur = gpu_fan()
206
- if cur is None or want is None:
207
- break
208
- if abs(cur - want) <= 5:
209
- break
210
- ok = True if cur is None else (want is None or abs(cur - want) <= 8)
211
- write_state(profile, ok, "gpu_fan=%s want=%s" % (cur, want))
212
- log("切到 %s 档 -> GPU 风扇 %s%%(目标 %s%%)%s" %
213
- (profile, cur, want, "" if ok else " ⚠ 未达预期"))
214
- return 0 if ok else 4
215
-
216
-
217
- def status():
218
- row = smi("name", "temperature.gpu", "fan.speed", "power.draw", "power.limit", "memory.used")
219
- if row:
220
- print("gpu : %s" % row[0].strip())
221
- print("temp : %s C fan: %s%% power: %s / %s W" % tuple(x.strip() for x in row[1:5]))
222
- print("vram : %s MiB" % row[5].strip())
223
- else:
224
- print("nvidia-smi 不可用")
225
- print("fanctl: %s" % ("running" if fancontrol_running() else "NOT running"))
226
- try:
227
- with open(STATE_FILE, "r", encoding="utf-8") as f:
228
- st = json.load(f)
229
- print("mode : %s (at %s, gpu_fan=%s%%)" % (st.get("profile"), st.get("at"), st.get("gpu_fan")))
230
- except Exception:
231
- print("mode : 未知(还没切过档)")
232
- for name in ("daily", "task"):
233
- p = os.path.join(CFG_DIR, name + ".json")
234
- print("%-6s: %s" % (name, "ok" if os.path.exists(p) else "缺失(运行 --make)"))
235
- return 0
236
-
237
-
238
- def main():
239
- ap = argparse.ArgumentParser()
240
- ap.add_argument("--status", action="store_true")
241
- ap.add_argument("--make", action="store_true")
242
- ap.add_argument("--force", action="store_true")
243
- ap.add_argument("--task", action="store_true")
244
- ap.add_argument("--daily", action="store_true")
245
- ap.add_argument("--apply", choices=["task", "daily"])
246
- a = ap.parse_args()
247
-
248
- if a.status:
249
- return status()
250
- if a.make:
251
- build(force=a.force)
252
- return status()
253
- if a.apply:
254
- return apply(a.apply)
255
- if a.task:
256
- return apply("task")
257
- if a.daily:
258
- return apply("daily")
259
- return status()
260
-
261
-
262
- if __name__ == "__main__":
263
- sys.exit(main())
1
+ # -*- coding: utf-8 -*-
2
+ """fan-mode.py —— FanControl 三档风扇 + 温度看门狗(日常 / 中间 / 训练)
3
+
4
+ 为什么重写(2026-12-04):
5
+ 原来只有 daily / task 两档,且切换全靠别的脚本手动调用 —— 没有任何进程在看温度,
6
+ 所以 GPU 跑到 88C 风扇还停在固定值上,"超过 80 度就切散热"从来没真正发生过。
7
+ 现在:三档固定占空比(不建曲线、不靠温度源判断,切过去就是死值),
8
+ 外加一个 --watch 看门狗:GPU/CPU 过 80C 进训练档,降回 74C 以下退日常档,中间走中间档。
9
+
10
+ 档位数值(主人 2026-12-04 给定,别再自己发挥):
11
+ 日常 daily : GPU 22 CPU 30 进风 23 出风 23
12
+ 中间 medium: GPU 61 CPU 50 进风 29 出风 29
13
+ 训练 train : GPU 70 CPU 66 进风 35 出风 35
14
+
15
+ 用法:
16
+ python scripts/fan-mode.py --status # 看当前温度/风扇/档位
17
+ python scripts/fan-mode.py --apply train # 切训练档
18
+ python scripts/fan-mode.py --apply medium
19
+ python scripts/fan-mode.py --apply daily
20
+ python scripts/fan-mode.py --task # 兼容旧调用,等价于 --apply train
21
+ python scripts/fan-mode.py --daily # 兼容旧调用
22
+ python scripts/fan-mode.py --watch # 常驻看门狗(>80C 自动进训练档)
23
+ """
24
+ import argparse
25
+ import ctypes
26
+ import json
27
+ import os
28
+ import subprocess
29
+ import sys
30
+ import time
31
+ from datetime import datetime
32
+
33
+ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
34
+ FC_EXE = r"C:\Program Files (x86)\FanControl\FanControl.exe"
35
+ FC_USER_CFG = r"C:\Program Files (x86)\FanControl\Configurations\userConfig.json"
36
+ CFG_DIR = os.path.join(ROOT, "config", "fan")
37
+ STATE_FILE = os.path.join(CFG_DIR, "state.json")
38
+ LOG_FILE = os.path.join(ROOT, "logs", "fan.log")
39
+ CREATE_NO_WINDOW = 0x08000000
40
+
41
+ # 档位定义:key -> (cpu, in, out, gpu)
42
+ PROFILES = {
43
+ "daily": {"cpu": 30, "in": 23, "out": 23, "gpu": 22},
44
+ "medium": {"cpu": 50, "in": 29, "out": 29, "gpu": 61},
45
+ "train": {"cpu": 66, "in": 35, "out": 35, "gpu": 70},
46
+ }
47
+ ALIAS = {"task": "train"} # 旧名字
48
+ # 看门狗阈值(带迟滞,避免在阈值上反复横跳)
49
+ T_HOT = 80 # >= 80C 进训练档
50
+ T_WARM = 74 # 74~80C 中间档
51
+ T_COOL = 64 # <= 64C 才回日常档。61% 风扇的平衡点就在 68~70C,阈值贴着平衡点会
52
+ # 每两分钟切一次(实测 10:30/10:32 连切),留到 64C 才不会来回叫
53
+ POLL_SEC = 15
54
+
55
+
56
+ def log(msg):
57
+ line = "%s %s" % (datetime.now().strftime("%Y-%m-%d %H:%M:%S"), msg)
58
+ print(line, flush=True)
59
+ try:
60
+ os.makedirs(os.path.dirname(LOG_FILE), exist_ok=True)
61
+ with open(LOG_FILE, "a", encoding="utf-8") as f:
62
+ f.write(line + "\n")
63
+ except OSError:
64
+ pass
65
+
66
+
67
+ def smi(*fields):
68
+ try:
69
+ out = subprocess.run(
70
+ ["nvidia-smi", "--query-gpu=" + ",".join(fields), "--format=csv,noheader,nounits"],
71
+ capture_output=True, text=True, timeout=15, creationflags=CREATE_NO_WINDOW)
72
+ rows = (out.stdout or "").strip().splitlines()
73
+ return [x.strip() for x in rows[0].split(",")] if rows else None
74
+ except Exception:
75
+ return None
76
+
77
+
78
+ def gpu_temp():
79
+ row = smi("temperature.gpu")
80
+ try:
81
+ return int(float(row[0]))
82
+ except Exception:
83
+ return None
84
+
85
+
86
+ def gpu_fan():
87
+ row = smi("fan.speed")
88
+ try:
89
+ return int(float(row[0]))
90
+ except Exception:
91
+ return None
92
+
93
+
94
+ def cpu_temp():
95
+ """CPU 温度:走 ACPI 热区。很多台式板子不暴露,读不到就返回 None(不阻塞判断)。"""
96
+ try:
97
+ out = subprocess.run(
98
+ ["powershell", "-NoProfile", "-Command",
99
+ "(Get-CimInstance -Namespace root/wmi -ClassName MSAcpi_ThermalZoneTemperature "
100
+ "-ErrorAction Stop | Select-Object -First 1).CurrentTemperature"],
101
+ capture_output=True, text=True, timeout=10, creationflags=CREATE_NO_WINDOW,
102
+ encoding="gbk", errors="ignore")
103
+ raw = (out.stdout or "").strip()
104
+ if not raw:
105
+ return None
106
+ return int(round(int(float(raw)) / 10.0 - 273.15))
107
+ except Exception:
108
+ return None
109
+
110
+
111
+ def _card_key(ident, nick):
112
+ hay_id = (ident or "").lower()
113
+ hay_nick = (nick or "").lower()
114
+ # 显卡卡的 Identifier 实际是 'NVApiWrapper/0-TU102-A/control/0'
115
+ # (旧代码写成 nvaapiwrapper,多了一个 a,所以三条配置里的 GPU 值从来没被改到)
116
+ if "nvapiwrapper" in hay_id or hay_id.startswith("nvapi"):
117
+ return "gpu"
118
+ if "cpu fan" in hay_nick:
119
+ return "cpu"
120
+ if "进风" in hay_nick:
121
+ return "in"
122
+ if "出风" in hay_nick:
123
+ return "out"
124
+ return None
125
+
126
+
127
+ def read_source_config():
128
+ with open(FC_USER_CFG, "r", encoding="utf-8-sig") as f:
129
+ return json.load(f)
130
+
131
+
132
+ def build(force=False):
133
+ """按三档目标值生成 daily/medium/train 三份模板;值不对就重建(不自作主张改数值)。"""
134
+ os.makedirs(CFG_DIR, exist_ok=True)
135
+ paths = {k: os.path.join(CFG_DIR, k + ".json") for k in PROFILES}
136
+ if not force and all(os.path.exists(p) for p in paths.values()):
137
+ # 模板被 FanControl 回写坏过(实测 medium 变成 35),所以存在也要核对数值
138
+ if all(_template_ok(p, PROFILES[k]) for k, p in paths.items()):
139
+ return paths
140
+ cfg = read_source_config()
141
+ for name, targets in PROFILES.items():
142
+ data = json.loads(json.dumps(cfg))
143
+ for card in data["FanControl"]["Controls"]:
144
+ key = _card_key(card.get("Identifier"), card.get("NickName"))
145
+ if not key:
146
+ continue
147
+ card["Enable"] = True
148
+ card["ManualControl"] = True # 固定值,不用曲线
149
+ card["ManualControlValue"] = int(targets[key])
150
+ tmp = paths[name] + ".tmp"
151
+ with open(tmp, "w", encoding="utf-8") as f:
152
+ json.dump(data, f, ensure_ascii=False, indent=2)
153
+ os.replace(tmp, paths[name])
154
+ log("已生成三档配置: " + ", ".join("%s(GPU %d%%)" % (k, v["gpu"]) for k, v in PROFILES.items()))
155
+ return paths
156
+
157
+
158
+ def _template_ok(path, targets):
159
+ try:
160
+ with open(path, "r", encoding="utf-8") as f:
161
+ data = json.load(f)
162
+ for card in data["FanControl"]["Controls"]:
163
+ key = _card_key(card.get("Identifier"), card.get("NickName"))
164
+ if key and int(card.get("ManualControlValue", -1)) != int(targets[key]):
165
+ return False
166
+ return True
167
+ except Exception:
168
+ return False
169
+
170
+
171
+ def fancontrol_running():
172
+ try:
173
+ out = subprocess.run(["tasklist", "/FI", "IMAGENAME eq FanControl.exe", "/NH"],
174
+ capture_output=True, text=True, timeout=15,
175
+ encoding="gbk", errors="ignore",
176
+ creationflags=CREATE_NO_WINDOW)
177
+ return "FanControl.exe" in (out.stdout or "")
178
+ except Exception:
179
+ return False
180
+
181
+
182
+ def write_state(profile, ok, note=""):
183
+ os.makedirs(CFG_DIR, exist_ok=True)
184
+ data = {"profile": profile if ok else "unknown", "ok": bool(ok),
185
+ "gpu_temp": gpu_temp(), "gpu_fan": gpu_fan(), "note": note,
186
+ "at": datetime.now().strftime("%Y-%m-%d %H:%M:%S")}
187
+ tmp = STATE_FILE + ".tmp"
188
+ with open(tmp, "w", encoding="utf-8") as f:
189
+ json.dump(data, f, ensure_ascii=False, indent=2)
190
+ os.replace(tmp, STATE_FILE)
191
+ return data
192
+
193
+
194
+ def current_profile():
195
+ try:
196
+ with open(STATE_FILE, "r", encoding="utf-8") as f:
197
+ return (json.load(f) or {}).get("profile")
198
+ except Exception:
199
+ return None
200
+
201
+
202
+ def is_admin():
203
+ """FanControl.exe -c 只有管理员才真正生效:非管理员调用会「成功返回、风扇不动」。"""
204
+ try:
205
+ return bool(ctypes.windll.shell32.IsUserAnAdmin())
206
+ except Exception:
207
+ return False
208
+
209
+
210
+ def relaunch_as_admin():
211
+ """把自己以管理员身份重开一次(UAC 弹窗)。换档/看门狗必须走这条路,否则等于没切。"""
212
+ params = " ".join('"%s"' % a for a in sys.argv[1:])
213
+ try:
214
+ rc = ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, params, None, 1)
215
+ return rc > 32
216
+ except Exception as e:
217
+ log("申请管理员权限失败: %s" % e)
218
+ return False
219
+
220
+
221
+ def apply(profile, wait=20):
222
+ name = ALIAS.get(profile, profile)
223
+ if name not in PROFILES:
224
+ log("未知档位: %s" % profile)
225
+ return 2
226
+ if not is_admin():
227
+ # 非管理员调 FanControl -c 会「返回成功但风扇不动」,那正是之前 88C 的原因
228
+ log("切 %s 档被拒绝:当前不是管理员,FanControl 接收配置但不执行" % name)
229
+ return 5
230
+ if not os.path.exists(FC_EXE):
231
+ log("找不到 FanControl.exe: %s" % FC_EXE)
232
+ return 3
233
+ cfg = build(force=False)[name] # 三档模板(只读,不给 FanControl 加载)
234
+ active = os.path.join(CFG_DIR, "active.json")
235
+ want = PROFILES[name]["gpu"]
236
+ # ★ 只改文件再 -c 重新加载并不可靠:实测同一进程里 reload 之后风扇还是按旧曲线跑
237
+ # (61% 目标实际只到 35~42%)。所以换档 = 先把 FanControl 停掉、再按新配置冷启动,
238
+ # 这样它一定是「启动即加载」,三档占空比才会真的落到风扇上。
239
+ try:
240
+ subprocess.run(["taskkill", "/IM", "FanControl.exe", "/F"], capture_output=True,
241
+ timeout=20, creationflags=CREATE_NO_WINDOW)
242
+ time.sleep(1.5)
243
+ except Exception:
244
+ pass
245
+ # 必须在停掉之后写 active.json:FanControl 退出时会把实时值回写它加载的那个文件
246
+ try:
247
+ with open(cfg, "r", encoding="utf-8") as f:
248
+ data = json.load(f)
249
+ with open(active, "w", encoding="utf-8") as f:
250
+ json.dump(data, f, ensure_ascii=False, indent=2)
251
+ except Exception as e:
252
+ log("写 active.json 失败: %s" % e)
253
+ return 3
254
+ try:
255
+ subprocess.Popen([FC_EXE, "-c", active, "-m"], creationflags=CREATE_NO_WINDOW)
256
+ except Exception as e:
257
+ log("拉起 FanControl 失败: %s" % e)
258
+ return 3
259
+
260
+ t0, cur = time.time(), gpu_fan()
261
+ while time.time() - t0 < wait:
262
+ time.sleep(2)
263
+ cur = gpu_fan()
264
+ if cur is None or abs(cur - want) <= 5:
265
+ break
266
+ ok = True if cur is None else (abs(cur - want) <= 8)
267
+ write_state(name, ok, "gpu_fan=%s want=%s" % (cur, want))
268
+ log("切到 %s 档 -> GPU 风扇 %s%%(目标 %s%%)%s" % (name, cur, want, "" if ok else " ⚠ 未达预期"))
269
+ return 0 if ok else 4
270
+
271
+
272
+ def pick_profile(temp, cur=None):
273
+ """带迟滞的三档判定:只在「确实该换」时才换,避免在阈值上每 15 秒来回跳。
274
+
275
+ >=80C → train(不管现在哪档)
276
+ 74~80C → 现在已经在 train 就保持(让它再压下去),否则 medium
277
+ 70~74C → 死区,保持不动
278
+ <=70C → daily
279
+ """
280
+ if temp is None:
281
+ return None
282
+ if temp >= T_HOT:
283
+ return "train"
284
+ if temp <= T_COOL:
285
+ return "daily"
286
+ if temp >= T_WARM:
287
+ return "train" if cur == "train" else "medium"
288
+ return None # 70~74 死区
289
+
290
+
291
+ def fan_ok(profile, tol=10):
292
+ """实际风扇是否真的到了该档的目标值(state.json 写的是「意图」,不是事实)。"""
293
+ f = gpu_fan()
294
+ if f is None:
295
+ return True
296
+ return abs(f - PROFILES[profile]["gpu"]) <= tol
297
+
298
+
299
+ def watch():
300
+ log("看门狗启动:>=%dC 训练档 / %d~%dC 中间档 / <=%dC 日常档,每 %ds 轮询"
301
+ % (T_HOT, T_WARM, T_HOT, T_COOL, POLL_SEC))
302
+ last_retry = 0.0
303
+ while True:
304
+ try:
305
+ tg, tc = gpu_temp(), cpu_temp()
306
+ hot = max([x for x in (tg, tc) if x is not None] or [None])
307
+ cur = current_profile()
308
+ want = pick_profile(hot, cur)
309
+ need = bool(want) and want != cur
310
+ # 配置写进去了但风扇没跟上(FanControl 自己回写配置就是这种坑)→ 60 秒重试一次
311
+ if want and not need and not fan_ok(want) and time.time() - last_retry > 60:
312
+ log("风扇没跟上:当前 %s%% / %s 档目标 %d%% → 重新下发"
313
+ % (gpu_fan(), want, PROFILES[want]["gpu"]))
314
+ last_retry = time.time()
315
+ need = True
316
+ if need:
317
+ log("温度 GPU=%s CPU=%s -> 切 %s 档" % (tg, tc, want))
318
+ apply(want)
319
+ time.sleep(POLL_SEC)
320
+ except KeyboardInterrupt:
321
+ log("看门狗退出")
322
+ return 0
323
+ except Exception as e:
324
+ log("看门狗异常(继续跑): %s" % e)
325
+ time.sleep(POLL_SEC)
326
+
327
+
328
+ def status():
329
+ row = smi("name", "temperature.gpu", "fan.speed", "power.draw", "power.limit", "memory.used")
330
+ if row:
331
+ print("gpu : %s" % row[0])
332
+ print("temp : %s C fan: %s%% power: %s / %s W" % tuple(row[1:5]))
333
+ print("vram : %s MiB" % row[5])
334
+ else:
335
+ print("nvidia-smi 不可用")
336
+ print("cpu : %s C" % cpu_temp())
337
+ print("fanctl: %s" % ("running" if fancontrol_running() else "NOT running"))
338
+ print("mode : %s" % (current_profile() or "未知(还没切过档)"))
339
+ for name in PROFILES:
340
+ p = os.path.join(CFG_DIR, name + ".json")
341
+ print("%-6s: %s (GPU %d%%)" % (name, "ok" if os.path.exists(p) else "缺失", PROFILES[name]["gpu"]))
342
+ return 0
343
+
344
+
345
+ def main():
346
+ ap = argparse.ArgumentParser()
347
+ ap.add_argument("--status", action="store_true")
348
+ ap.add_argument("--make", action="store_true")
349
+ ap.add_argument("--force", action="store_true")
350
+ ap.add_argument("--watch", action="store_true")
351
+ ap.add_argument("--task", action="store_true")
352
+ ap.add_argument("--daily", action="store_true")
353
+ ap.add_argument("--apply", choices=list(PROFILES) + ["task"])
354
+ a = ap.parse_args()
355
+
356
+ if a.status:
357
+ return status()
358
+ if a.make:
359
+ build(force=a.force)
360
+ return status()
361
+ # 换档 / 看门狗:非管理员先自我提权重开,否则切了等于没切
362
+ if (a.watch or a.apply or a.task or a.daily) and not is_admin():
363
+ log("非管理员启动,正在申请管理员权限重开(UAC 请点「是」)")
364
+ if relaunch_as_admin():
365
+ return 0
366
+ log("没有拿到管理员权限 —— 风扇不会真的动")
367
+ return 5
368
+ if a.watch:
369
+ return watch()
370
+ if a.apply:
371
+ return apply(a.apply)
372
+ if a.task:
373
+ return apply("train")
374
+ if a.daily:
375
+ return apply("daily")
376
+ return status()
377
+
378
+
379
+ if __name__ == "__main__":
380
+ sys.exit(main())