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
@@ -0,0 +1,110 @@
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ """qqheader.py — 直接拿 nt_msg.db 头部字段试所有可能(密钥可能就写在头里)"""
4
+ import base64, hashlib, itertools, os, re, sys
5
+
6
+ from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
7
+
8
+ P = r'F:\Programs\QQ\files\Tencent Files\2394482710\nt_qq\nt_db\nt_msg.db'
9
+ MAGIC = b'SQLite format 3\x00'
10
+
11
+
12
+ def dec(key, iv, ct):
13
+ d = Cipher(algorithms.AES(key), modes.CBC(iv)).decryptor()
14
+ return d.update(ct) + d.finalize()
15
+
16
+
17
+ def main(p=P):
18
+ data = open(p, 'rb').read(16384)
19
+ size = os.path.getsize(p)
20
+ print('size', size, 'size%4096', size % 4096)
21
+ m = re.search(rb'([0-9a-f]{128})', data[:400])
22
+ if not m:
23
+ print('没找到 128 hex'); return
24
+ hx = m.group(1).decode()
25
+ print('128hex @', m.start())
26
+ raw = bytes.fromhex(hx)
27
+ a, b = raw[:32], raw[32:]
28
+ print('a=', a.hex())
29
+ print('b=', b.hex())
30
+ print('b == a^0x3a ?', b == bytes(x ^ 0x3a for x in a))
31
+ print('b == a^0x3a(first16 only) ?', b[:16] == bytes(x ^ 0x3a for x in a[:16]))
32
+
33
+ # 候选密钥来源
34
+ keys = {
35
+ 'a32': a, 'b32': b, 'a16x2': a[:16] + a[:16],
36
+ 'hex_a': a, 'hex_b': b,
37
+ }
38
+ # 也试 KDF:passphrase = 128hex 字符串 / a / b,salt = a/b/文件前16
39
+ salts = {'a': a, 'b': b}
40
+
41
+ # 页起始候选
42
+ page_starts = [0, 157, 4096]
43
+ reserves = [16, 48, 80]
44
+ hit = None
45
+ for name, k in keys.items():
46
+ for ps in page_starts:
47
+ for r in reserves:
48
+ for (sn, salt) in salts.items():
49
+ iv_pos = ps + 4096 - r
50
+ if iv_pos + 16 > len(data):
51
+ continue
52
+ iv = data[iv_pos:iv_pos + 16]
53
+ ct = data[ps + 16:iv_pos]
54
+ if len(ct) < 16:
55
+ continue
56
+ try:
57
+ if dec(k, iv, ct[:16]) == MAGIC:
58
+ hit = ('rawkey', name, ps, r, sn); break
59
+ except Exception:
60
+ pass
61
+ if hit:
62
+ break
63
+ if hit:
64
+ break
65
+ if hit:
66
+ break
67
+
68
+ if not hit:
69
+ # KDF 组合(少量)
70
+ cnt = 0
71
+ for pname, pw in (('hex128', hx.encode()), ('a', a), ('b', b), ('hexA', a.hex().encode()), ('hexB', b.hex().encode())):
72
+ for sn, salt in salts.items():
73
+ for it in (4000, 64000, 256000):
74
+ for hl in ('sha1', 'sha512'):
75
+ try:
76
+ k = hashlib.pbkdf2_hmac(hl, pw, salt, it, 32)
77
+ except Exception:
78
+ continue
79
+ cnt += 1
80
+ for ps in page_starts:
81
+ for r in reserves:
82
+ iv_pos = ps + 4096 - r
83
+ if iv_pos + 16 > len(data):
84
+ continue
85
+ iv = data[iv_pos:iv_pos + 16]
86
+ ct = data[ps + 16:iv_pos]
87
+ if len(ct) < 16:
88
+ continue
89
+ try:
90
+ if dec(k, iv, ct[:16]) == MAGIC:
91
+ hit = ('kdf', pname, sn, it, hl, ps, r); break
92
+ except Exception:
93
+ pass
94
+ if hit:
95
+ break
96
+ if hit:
97
+ break
98
+ if hit:
99
+ break
100
+ if hit:
101
+ break
102
+ if hit:
103
+ break
104
+ print('KDF 试了', cnt, '组')
105
+
106
+ print('HIT:', hit if hit else '无')
107
+
108
+
109
+ if __name__ == '__main__':
110
+ main(sys.argv[1] if len(sys.argv) > 1 else P)
@@ -0,0 +1,113 @@
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ """qqkey2.py — 从 QQ 进程内存里捞出「口令串」并做 SQLCipher 组合校验(本地只读)
4
+
5
+ 思路(2026-12-02 晚):QQNT 的 nt_msg.db 页 1 在偏移 1024,前 16 字节是盐(与
6
+ nt_msg.db-first.material 完全一致)。裸密钥模式全内存扫已排除,那它就是用
7
+ WCDB/SQLCipher 的「口令」模式 —— 口令很可能以 32/64 位 hex 字符串躺在内存里。
8
+ 先把这种字符串全捞出来(数量少),再挨个 KDF 校验。
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import ctypes
13
+ import hashlib
14
+ import os
15
+ import re
16
+ import sys
17
+ import time
18
+
19
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
20
+ import sqlcipher_probe as sp # noqa: E402
21
+
22
+ PAGE = 4096
23
+ MAGIC = b'SQLite format 3\x00'
24
+ DB = r'F:\Programs\QQ\files\Tencent Files\2394482710\nt_qq\nt_db\nt_msg.db'
25
+ PAGE_START = 1024
26
+
27
+
28
+ def collect_hex_strings(exe: str, minlen: int = 16, maxlen: int = 128, cap: int = 200000):
29
+ """收集内存里长度在 [minlen,maxlen] 之间的 hex 字符串(ASCII 与 UTF-16LE 都收)"""
30
+ pat = re.compile(rb'(?<![0-9a-fA-F])[0-9a-fA-F]{%d,%d}(?![0-9a-fA-F])' % (minlen, maxlen))
31
+ out = {}
32
+ for pid in sp.pids_of(exe):
33
+ try:
34
+ for _b, data in sp.read_regions(pid):
35
+ for m in pat.finditer(data):
36
+ s = m.group(0).decode('ascii', 'ignore')
37
+ out.setdefault(s, 0)
38
+ out[s] += 1
39
+ # UTF-16LE:b'a\0b\0c\0'
40
+ for m in re.finditer(rb'(?:[0-9a-fA-F]\x00){%d,%d}' % (minlen, maxlen), data):
41
+ s = m.group(0).decode('utf-16le', 'ignore')
42
+ out.setdefault(s, 0)
43
+ out[s] += 1
44
+ if len(out) > cap:
45
+ return out
46
+ except OSError:
47
+ continue
48
+ return out
49
+
50
+
51
+ def varint_ok(buf, i):
52
+ v = 0; s = 0
53
+ while True:
54
+ c = buf[i]; i += 1; v |= (c & 0x7f) << s; s += 7
55
+ if not c & 0x80:
56
+ return v, i
57
+
58
+
59
+ def try_one(args):
60
+ (pw, head, combos) = args
61
+ from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
62
+ salt = head[:16]
63
+ for (halg, it, reserve) in combos:
64
+ try:
65
+ key = hashlib.pbkdf2_hmac(halg, pw, salt, it, 32)
66
+ except Exception:
67
+ continue
68
+ iv_pos = PAGE - reserve
69
+ iv = head[iv_pos:iv_pos + 16]
70
+ ct = head[16:iv_pos]
71
+ if len(ct) < 16:
72
+ continue
73
+ try:
74
+ d = Cipher(algorithms.AES(key), modes.CBC(iv)).decryptor()
75
+ if d.update(ct[:16]) == MAGIC:
76
+ return (pw.decode('ascii', 'ignore'), halg, it, reserve)
77
+ except Exception:
78
+ pass
79
+ return None
80
+
81
+
82
+ def main():
83
+ with open(DB, 'rb') as f:
84
+ f.seek(PAGE_START)
85
+ head = f.read(PAGE)
86
+ print('salt:', head[:16].hex(), flush=True)
87
+ t0 = time.time()
88
+ strings = collect_hex_strings('QQ.exe')
89
+ print(f'内存里 hex 串 {len(strings)} 个(去重后),{time.time()-t0:.1f}s', flush=True)
90
+ lens = {}
91
+ for s in strings:
92
+ lens[len(s)] = lens.get(len(s), 0) + 1
93
+ print('长度分布:', dict(sorted(lens.items())[:12]), flush=True)
94
+
95
+ # 优先:16/32/64 字节对应的 hex 长度(32/64/128)
96
+ cands = [s for s in strings if len(s) in (32, 64, 128)]
97
+ print('候选口令', len(cands), '个', flush=True)
98
+ combos = [('sha1', 64000, 48), ('sha512', 64000, 80), ('sha512', 256000, 80), ('sha1', 4000, 48)]
99
+ import multiprocessing as mp
100
+ tasks = [(s.encode(), head, combos) for s in cands]
101
+ hit = None
102
+ with mp.Pool(max(2, (os.cpu_count() or 4) - 2)) as pool:
103
+ for i, r in enumerate(pool.imap_unordered(try_one, tasks, chunksize=8)):
104
+ if r:
105
+ hit = r; break
106
+ if (i + 1) % 200 == 0:
107
+ print(f' {i+1}/{len(cands)} … {time.time()-t0:.0f}s', flush=True)
108
+ pool.terminate()
109
+ print('命中:', hit if hit else '无', f'({time.time()-t0:.0f}s)')
110
+
111
+
112
+ if __name__ == '__main__':
113
+ main()
@@ -0,0 +1,153 @@
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ qqprobe.py — QQNT 数据库「密钥 + 布局」联合探测(本地只读)
5
+
6
+ QQNT 的 nt_msg.db 头 16 字节是 "SQLite header 3\\0"(不是标准 SQLite 头,也不是盐)。
7
+ 社区实现各有说法,所以这里不猜:把「候选密钥」×「常见 SQLCipher 布局」全试一遍,
8
+ 用已知明文 "SQLite format 3\\0" 判定。
9
+
10
+ 用法:
11
+ python scripts/chat-archive/qqprobe.py --exe QQ.exe --db <nt_msg.db> [--max-kdf 400]
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import argparse
16
+ import ctypes
17
+ import hashlib
18
+ import os
19
+ import re
20
+ import sys
21
+ import time
22
+
23
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
24
+ import sqlcipher_probe as sp # noqa: E402
25
+
26
+ PAGE = 4096
27
+ MAGIC = b'SQLite format 3\x00'
28
+
29
+
30
+ def dec_block(key: bytes, iv: bytes, ct: bytes) -> bytes:
31
+ from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
32
+ d = Cipher(algorithms.AES(key), modes.CBC(iv)).decryptor()
33
+ return d.update(ct) + d.finalize()
34
+
35
+
36
+ def layouts(head: bytes):
37
+ """(名字, 页偏移, 盐, 保留区) —— 保留区=页面末尾 IV+HMAC 的字节数"""
38
+ return [
39
+ ('std80', 0, head[0:16], 80),
40
+ ('hdr16+80', 16, head[16:32], 80),
41
+ ('std48', 0, head[0:16], 48),
42
+ ('hdr16+48', 16, head[16:32], 48),
43
+ ('std16', 0, head[0:16], 16),
44
+ ('hdr16+16', 16, head[16:32], 16),
45
+ ]
46
+
47
+
48
+ def try_key(head: bytes, key: bytes, label: str = '') -> str | None:
49
+ """返回命中的布局名,未命中返回 None"""
50
+ for name, off, salt, reserve in layouts(head):
51
+ iv_pos = PAGE - reserve
52
+ if iv_pos <= off or iv_pos + 16 > PAGE:
53
+ continue
54
+ iv = head[iv_pos:iv_pos + 16]
55
+ ct = head[off:iv_pos]
56
+ try:
57
+ if dec_block(key, iv, ct[:16]) == MAGIC:
58
+ return f'{name}{label}'
59
+ except Exception:
60
+ pass
61
+ return None
62
+
63
+
64
+ def collect(exe: str, needles: list[str], span: int, cap: int):
65
+ """收集候选:hex 串优先(key 常以 64 位 hex 存在内存里),其余是 32 字节窗口"""
66
+ hexc, raws, seen = [], [], set()
67
+ hexre = re.compile(rb'[0-9a-fA-F]{64}')
68
+ for pid in sp.pids_of(exe):
69
+ try:
70
+ for _b, data in sp.read_regions(pid):
71
+ for nd in needles:
72
+ for enc in (nd.encode('utf-8'), nd.encode('utf-16le')):
73
+ st = 0
74
+ while True:
75
+ i = data.find(enc, st)
76
+ if i < 0:
77
+ break
78
+ st = i + 1
79
+ lo, hi = max(0, i - span), min(len(data), i + span)
80
+ chunk = data[lo:hi]
81
+ for m in hexre.finditer(chunk):
82
+ try:
83
+ b = bytes.fromhex(m.group(0).decode())
84
+ except Exception:
85
+ continue
86
+ if b not in seen:
87
+ seen.add(b); hexc.append(b)
88
+ for o in range(0, max(0, len(chunk) - 32), 8):
89
+ b = chunk[o:o + 32]
90
+ if b not in seen:
91
+ seen.add(b); raws.append(b)
92
+ if len(raws) >= cap:
93
+ return hexc, raws
94
+ except OSError:
95
+ continue
96
+ return hexc, raws
97
+
98
+
99
+ def main():
100
+ ap = argparse.ArgumentParser()
101
+ ap.add_argument('--exe', default='QQ.exe')
102
+ ap.add_argument('--db', required=True)
103
+ ap.add_argument('--needle', action='append', default=[])
104
+ ap.add_argument('--span', type=int, default=4096)
105
+ ap.add_argument('--cap', type=int, default=30000)
106
+ ap.add_argument('--max-kdf', type=int, default=400)
107
+ a = ap.parse_args()
108
+
109
+ with open(a.db, 'rb') as f:
110
+ head = f.read(PAGE)
111
+ print('头 16 字节:', head[:16].hex(), repr(head[:16]))
112
+ needles = a.needle or [os.path.basename(a.db), 'nt_msg.db']
113
+ print('进程:', sp.pids_of(a.exe))
114
+ t0 = time.time()
115
+ hexc, raws = collect(a.exe, needles, a.span, a.cap)
116
+ print(f'候选: hex {len(hexc)} 个 / 裸窗口 {len(raws)} 个({time.time()-t0:.1f}s)', flush=True)
117
+
118
+ hit = None
119
+ # ① 裸密钥模式(便宜,先把所有候选过一遍)
120
+ for b in hexc + raws:
121
+ r = try_key(head, b, '(raw)')
122
+ if r:
123
+ hit = (r, b.hex()); break
124
+ print('raw 模式:', '命中 ' + str(hit) if hit else '未命中', flush=True)
125
+
126
+ # ② KDF 模式(贵,只试 hex 候选和前 N 个裸窗口)
127
+ if not hit:
128
+ tried = 0
129
+ for b in (hexc + raws)[:max(1, a.max_kdf)]:
130
+ for it in (256000, 64000, 4000):
131
+ for off, reserve in ((0, 80), (16, 80), (0, 48), (16, 48)):
132
+ salt = head[0:16]
133
+ try:
134
+ key = hashlib.pbkdf2_hmac('sha512', b, salt, it, 32)
135
+ except Exception:
136
+ continue
137
+ r = try_key(head, key, f'(kdf{it})')
138
+ if r:
139
+ hit = (r, b.hex()); break
140
+ if hit:
141
+ break
142
+ tried += 1
143
+ if hit:
144
+ break
145
+ if tried % 20 == 0:
146
+ print(f' kdf {tried} 个候选… {time.time()-t0:.0f}s', flush=True)
147
+ print('kdf 模式:', '命中 ' + str(hit) if hit else '未命中', flush=True)
148
+ if hit:
149
+ print('KEY', hit[1], 'LAYOUT', hit[0])
150
+
151
+
152
+ if __name__ == '__main__':
153
+ main()
@@ -0,0 +1,163 @@
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ screen-collect.py — 「土办法」:截图 + 本地 OCR,把聊天窗口里看得见的文字逐屏记下来
5
+
6
+ 为什么要有它:微信 4.x / QQNT 的库是 SQLCipher,拿不到密钥就读不了(今天已验证两种
7
+ 思路都失败)。但窗口里显示的正文,人眼能看、本地 OCR 也能读 —— 全程不联网、不上传。
8
+
9
+ 安全性:只读屏幕 + 可选滚轮滚动;不点任何按钮、不发送任何消息;图片默认用完即删,
10
+ 只留文本。所有产物落在 data/chat-archive/screen/(已在 .gitignore 的 data/ 下)。
11
+
12
+ 用法:
13
+ python scripts/chat-archive/screen-collect.py --list
14
+ python scripts/chat-archive/screen-collect.py --title 启星 --shots 1 --dry-run
15
+ python scripts/chat-archive/screen-collect.py --title 启星 --shots 60 --scroll
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import argparse
20
+ import ctypes
21
+ import ctypes.wintypes as wt
22
+ import hashlib
23
+ import io
24
+ import json
25
+ import os
26
+ import sys
27
+ import time
28
+
29
+ import requests
30
+ from PIL import ImageGrab
31
+
32
+ user32 = ctypes.WinDLL('user32', use_last_error=True)
33
+ OCR_URL = 'http://127.0.0.1:8188/ocr'
34
+ OUT_ROOT = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))),
35
+ 'data', 'chat-archive', 'screen')
36
+
37
+
38
+ def list_windows() -> list[tuple[int, str, tuple[int, int, int, int]]]:
39
+ out = []
40
+
41
+ @ctypes.WINFUNCTYPE(wt.BOOL, wt.HWND, wt.LPARAM)
42
+ def cb(hwnd, _l):
43
+ if not user32.IsWindowVisible(hwnd):
44
+ return True
45
+ n = user32.GetWindowTextLengthW(hwnd)
46
+ if n <= 0:
47
+ return True
48
+ buf = ctypes.create_unicode_buffer(n + 1)
49
+ user32.GetWindowTextW(hwnd, buf, n + 1)
50
+ title = buf.value.strip()
51
+ if title:
52
+ r = wt.RECT()
53
+ user32.GetWindowRect(hwnd, ctypes.byref(r))
54
+ out.append((hwnd, title, (r.left, r.top, r.right - r.left, r.bottom - r.top)))
55
+ return True
56
+
57
+ user32.EnumWindows(cb, 0)
58
+ return out
59
+
60
+
61
+ def find_window(sub: str):
62
+ for hwnd, title, rect in list_windows():
63
+ if sub in title and rect[2] > 300 and rect[3] > 300:
64
+ return hwnd, title, rect
65
+ return None
66
+
67
+
68
+ def show_window(hwnd: int):
69
+ user32.ShowWindow(hwnd, 9) # SW_RESTORE
70
+ user32.SetForegroundWindow(hwnd)
71
+ time.sleep(0.35)
72
+
73
+
74
+ def grab(rect, crop_left_pct: float = 0.0):
75
+ x, y, w, h = rect
76
+ box = (x + int(w * crop_left_pct / 100), y, x + w, y + h)
77
+ return ImageGrab.grab(bbox=box, all_screens=True)
78
+
79
+
80
+ def ocr(img) -> dict:
81
+ buf = io.BytesIO()
82
+ img.save(buf, format='PNG')
83
+ buf.seek(0)
84
+ r = requests.post(OCR_URL, files={'file': ('shot.png', buf, 'image/png')},
85
+ data={'model': 'paddleocr'}, timeout=180)
86
+ r.raise_for_status()
87
+ return r.json()
88
+
89
+
90
+ def scroll_at(rect, clicks: int = -3):
91
+ x, y, w, h = rect
92
+ user32.SetCursorPos(x + w // 2, y + h // 2)
93
+ for _ in range(abs(clicks)):
94
+ user32.mouse_event(0x0800, 0, 0, 120 if clicks > 0 else -120, 0) # MOUSEEVENTF_WHEEL
95
+ time.sleep(0.05)
96
+ time.sleep(0.45)
97
+
98
+
99
+ def main():
100
+ ap = argparse.ArgumentParser()
101
+ ap.add_argument('--list', action='store_true')
102
+ ap.add_argument('--title', default='')
103
+ ap.add_argument('--shots', type=int, default=1)
104
+ ap.add_argument('--scroll', action='store_true', help='每屏后向上滚(看更早的消息)')
105
+ ap.add_argument('--wheel', type=int, default=-3, help='滚轮格数(负=向上)')
106
+ ap.add_argument('--dry-run', action='store_true', help='只截一张、不写文件')
107
+ ap.add_argument('--crop-left', type=float, default=0.0, help='裁掉左侧会话列表百分比')
108
+ ap.add_argument('--min-score', type=float, default=0.5)
109
+ a = ap.parse_args()
110
+
111
+ if a.list:
112
+ for hwnd, title, rect in list_windows():
113
+ print(f'{hwnd:>10} {rect[2]}x{rect[3]:<5} {title[:60]}')
114
+ return
115
+ if not a.title:
116
+ print('要用 --title 指定窗口(先 --list 看看)'); return
117
+
118
+ w = find_window(a.title)
119
+ if not w:
120
+ print('没找到窗口:', a.title); return
121
+ hwnd, title, rect = w
122
+ print('窗口:', title, rect)
123
+ show_window(hwnd)
124
+
125
+ conv = title.replace('/', '_').replace('\\', '_')[:40]
126
+ out_dir = os.path.join(OUT_ROOT, conv)
127
+ if not a.dry_run:
128
+ os.makedirs(out_dir, exist_ok=True)
129
+ out_file = os.path.join(out_dir, 'ocr-%s.jsonl' % time.strftime('%Y%m%d'))
130
+ seen = set()
131
+ no_new = 0
132
+ t0 = time.time()
133
+ for i in range(a.shots):
134
+ img = grab(rect, a.crop_left)
135
+ t1 = time.time()
136
+ res = ocr(img)
137
+ lines = [x for x in res.get('lines', []) if float(x.get('score', 0)) >= a.min_score]
138
+ new = []
139
+ for ln in lines:
140
+ key = hashlib.md5(ln['text'].encode('utf-8')).hexdigest()
141
+ if key in seen:
142
+ continue
143
+ seen.add(key)
144
+ new.append({'t': ln['text'], 'y': round(ln['box'][0][1], 1), 's': ln.get('score')})
145
+ print(f'[{i+1}/{a.shots}] OCR {len(lines)} 行,新 {len(new)} 行,{(time.time()-t1):.1f}s')
146
+ if not a.dry_run:
147
+ with open(out_file, 'a', encoding='utf-8') as f:
148
+ f.write(json.dumps({'at': time.strftime('%Y-%m-%d %H:%M:%S'), 'shot': i,
149
+ 'lines': new}, ensure_ascii=False) + '\n')
150
+ no_new = no_new + 1 if not new else 0
151
+ if a.dry_run:
152
+ print(json.dumps([x['text'] for x in lines][:20], ensure_ascii=False))
153
+ break
154
+ if a.scroll:
155
+ scroll_at(rect, a.wheel)
156
+ if no_new >= 3:
157
+ print('连续 3 屏没有新内容,停(可能到顶了)')
158
+ break
159
+ print(f'完成,用时 {time.time()-t0:.0f}s,累计 {len(seen)} 行,输出 {out_file if not a.dry_run else "(dry-run)"}')
160
+
161
+
162
+ if __name__ == '__main__':
163
+ sys.exit(main())