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,143 @@
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ """extract-memory.py — 只读导出 memory.db 里的明文素材(给 SFT 用)
4
+
5
+ 为什么单独一个脚本:
6
+ memory.db 里 mem.text 是 AES-256-GCM 加密的(enc1: 前缀),SQL 直接查出来是乱码;
7
+ 但模型真正需要的是「他是谁 / 她怎么说人话 / 我们之间是什么关系」,
8
+ 这些都在 mem(fact/event/preference/relation)、persona(slice 摘要)、belief(好感度) 里。
9
+ 所以这里只做一件事:解密 + 分门别类写成 jsonl,**绝不写回原库、绝不改原库**。
10
+
11
+ 产物(默认 archive/sft4/src/):
12
+ memory.jsonl 解密后的记忆条目(scope/kind/subj/text/ts/tags)
13
+ persona.jsonl persona 表(slice 摘要 / 设定条目)
14
+ belief.json 好感度/幽默感等连续量
15
+ chat.jsonl chat 表导出(明文,含 dir=in/out,供交叉校验导出文件是否漏消息)
16
+
17
+ 用法:
18
+ python scripts/chat-archive/extract-memory.py
19
+ python scripts/chat-archive/extract-memory.py --db F:\\qqbot\\dshqqbot\\.qqbot\\memory.db --out archive/sft4/src
20
+ """
21
+ from __future__ import annotations
22
+
23
+ import argparse
24
+ import base64
25
+ import collections
26
+ import json
27
+ import os
28
+ import sqlite3
29
+ import sys
30
+
31
+ ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
32
+ ENC_PREFIX = 'enc1:'
33
+ IV_LEN, TAG_LEN = 12, 16
34
+
35
+
36
+ def load_key(db_path: str):
37
+ """密钥固定落在 {root}/.qqbot/secrets/memory.key(64 位 hex)"""
38
+ root = os.path.dirname(os.path.dirname(os.path.abspath(db_path)))
39
+ p = os.path.join(root, '.qqbot', 'secrets', 'memory.key')
40
+ if not os.path.exists(p):
41
+ return None, p
42
+ hex_ = open(p, encoding='utf-8').read().strip()
43
+ if len(hex_) != 64:
44
+ return None, p
45
+ return bytes.fromhex(hex_), p
46
+
47
+
48
+ def make_dec(key):
49
+ from cryptography.hazmat.primitives.ciphers.aead import AESGCM
50
+ if not key:
51
+ return lambda s: '' if str(s or '').startswith(ENC_PREFIX) else str(s or '')
52
+ aes = AESGCM(key)
53
+
54
+ def dec(stored):
55
+ s = str(stored or '')
56
+ if not s.startswith(ENC_PREFIX):
57
+ return s
58
+ try:
59
+ buf = base64.b64decode(s[len(ENC_PREFIX):])
60
+ # 存储顺序是 iv(12) + tag(16) + 密文;AESGCM 要的是 (密文 + tag)
61
+ iv, tag, body = buf[:IV_LEN], buf[IV_LEN:IV_LEN + TAG_LEN], buf[IV_LEN + TAG_LEN:]
62
+ return aes.decrypt(iv, body + tag, None).decode('utf-8')
63
+ except Exception:
64
+ return ''
65
+ return dec
66
+
67
+
68
+ def main():
69
+ ap = argparse.ArgumentParser()
70
+ ap.add_argument('--db', default=os.path.join(ROOT, 'dshqqbot', '.qqbot', 'memory.db'))
71
+ ap.add_argument('--out', default=os.path.join(ROOT, 'archive', 'sft4', 'src'))
72
+ a = ap.parse_args()
73
+
74
+ if not os.path.exists(a.db):
75
+ print('数据库不存在:', a.db)
76
+ return 1
77
+ os.makedirs(a.out, exist_ok=True)
78
+
79
+ key, key_path = load_key(a.db)
80
+ dec = make_dec(key)
81
+ print(f'密钥:{key_path} → {"已加载" if key else "缺失(密文将输出为空串)"}')
82
+
83
+ con = sqlite3.connect(f'file:{a.db}?mode=ro', uri=True) # 只读打开,物理上不可能改库
84
+ con.row_factory = sqlite3.Row
85
+ cur = con.cursor()
86
+
87
+ tags = collections.defaultdict(list)
88
+ try:
89
+ for r in cur.execute('select scope, name, mem_id from mem_tag'):
90
+ tags[(r['scope'], r['mem_id'])].append(r['name'])
91
+ except sqlite3.Error:
92
+ pass
93
+
94
+ rows, empty = [], 0
95
+ for r in cur.execute('select id, scope, kind, subj, text, ts, priority, pinned_at from mem order by ts'):
96
+ t = dec(r['text']).strip()
97
+ if not t:
98
+ empty += 1
99
+ continue
100
+ rows.append({'id': r['id'], 'scope': r['scope'], 'kind': r['kind'], 'subj': r['subj'],
101
+ 'text': t, 'ts': r['ts'], 'priority': r['priority'] or 0,
102
+ 'pinned': bool(r['pinned_at']), 'tag': tags.get((r['scope'], r['id']), [])})
103
+
104
+ with open(os.path.join(a.out, 'memory.jsonl'), 'w', encoding='utf-8') as f:
105
+ for r in rows:
106
+ f.write(json.dumps(r, ensure_ascii=False) + '\n')
107
+
108
+ persona = []
109
+ for r in cur.execute('select id, scope, ckey, cvalue, weight, ts from persona order by ts'):
110
+ v = dec(r['cvalue']).strip() # persona 通常是明文,密文也能解
111
+ if v:
112
+ persona.append({'id': r['id'], 'scope': r['scope'], 'ckey': r['ckey'],
113
+ 'cvalue': v, 'weight': r['weight'], 'ts': r['ts']})
114
+ with open(os.path.join(a.out, 'persona.jsonl'), 'w', encoding='utf-8') as f:
115
+ for r in persona:
116
+ f.write(json.dumps(r, ensure_ascii=False) + '\n')
117
+
118
+ belief = [dict(r) for r in cur.execute('select * from belief')]
119
+ json.dump(belief, open(os.path.join(a.out, 'belief.json'), 'w', encoding='utf-8'),
120
+ ensure_ascii=False, indent=2)
121
+
122
+ chats = []
123
+ for r in cur.execute('select scope, ts, dir, sender, kind, text from chat order by ts'):
124
+ t = dec(r['text']).strip()
125
+ if t and r['kind'] in (None, '', 'text'):
126
+ chats.append({'scope': r['scope'], 'ts': r['ts'], 'dir': r['dir'],
127
+ 'sender': r['sender'], 'text': t})
128
+ with open(os.path.join(a.out, 'chat.jsonl'), 'w', encoding='utf-8') as f:
129
+ for r in chats:
130
+ f.write(json.dumps(r, ensure_ascii=False) + '\n')
131
+
132
+ stat = {'mem_total': len(rows), 'mem_empty_or_failed': empty,
133
+ 'by_kind': dict(collections.Counter(r['kind'] for r in rows).most_common()),
134
+ 'persona': len(persona), 'belief': len(belief), 'chat': len(chats)}
135
+ json.dump(stat, open(os.path.join(a.out, 'extract-stats.json'), 'w', encoding='utf-8'),
136
+ ensure_ascii=False, indent=2)
137
+ print(json.dumps(stat, ensure_ascii=False, indent=2))
138
+ print('输出目录:', os.path.abspath(a.out))
139
+ return 0
140
+
141
+
142
+ if __name__ == '__main__':
143
+ sys.exit(main())
@@ -0,0 +1,182 @@
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ inventory.py — 本机聊天数据盘点(离线,只读)
5
+
6
+ 回答一个问题:要把「木囿 / 启星」2023–2026 的微信+QQ 聊天本地备份下来,
7
+ 本机到底有多少东西、在哪儿、加没加密、大概要跑多久。
8
+
9
+ 用法:
10
+ python scripts/chat-archive/inventory.py
11
+ python scripts/chat-archive/inventory.py --json
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import argparse
16
+ import json
17
+ import os
18
+ import time
19
+
20
+ WECHAT_ROOTS = [
21
+ r'F:\Programs\Wechat\files\xwechat_files',
22
+ r'C:\Users\Administrator\Documents\WeChat Files',
23
+ ]
24
+ QQ_ROOTS = [
25
+ r'F:\Programs\QQ\files\Tencent Files',
26
+ r'C:\Users\Administrator\Documents\Tencent Files',
27
+ ]
28
+ SIDECAR_MEDIA = ['Image', 'Video', 'Audio', 'FileRecv', 'emoji', 'Emoji', 'attach', 'msg', 'image', 'video', 'voice']
29
+
30
+
31
+ def human(n: float) -> str:
32
+ for u in ['B', 'KB', 'MB', 'GB', 'TB']:
33
+ if n < 1024 or u == 'TB':
34
+ return f'{n:.1f}{u}'
35
+ n /= 1024
36
+ return f'{n:.1f}TB'
37
+
38
+
39
+ def head_of(p: str, n: int = 16) -> bytes:
40
+ try:
41
+ with open(p, 'rb') as f:
42
+ return f.read(n)
43
+ except Exception:
44
+ return b''
45
+
46
+
47
+ def is_plain_sqlite(p: str) -> bool:
48
+ return head_of(p, 15) == b'SQLite format 3'
49
+
50
+
51
+ def walk(root: str, exts=('.db',)):
52
+ out = []
53
+ if not os.path.isdir(root):
54
+ return out
55
+ for dirpath, _dirs, files in os.walk(root):
56
+ for fn in files:
57
+ if fn.lower().endswith(exts) and ('-wal' not in fn and '-shm' not in fn):
58
+ p = os.path.join(dirpath, fn)
59
+ try:
60
+ out.append((p, os.path.getsize(p), os.path.getmtime(p)))
61
+ except OSError:
62
+ pass
63
+ return out
64
+
65
+
66
+ def inventory() -> dict:
67
+ rep = {'at': time.strftime('%Y-%m-%d %H:%M:%S'), 'wechat': [], 'qq': [], 'media': [], 'summary': {}}
68
+ for root in WECHAT_ROOTS:
69
+ if not os.path.isdir(root):
70
+ continue
71
+ for acct in sorted(os.listdir(root)):
72
+ acc_dir = os.path.join(root, acct)
73
+ storage = os.path.join(acc_dir, 'db_storage')
74
+ if not os.path.isdir(storage):
75
+ continue
76
+ files = walk(storage)
77
+ files.sort(key=lambda x: -x[1])
78
+ for p, size, mtime in files[:12]:
79
+ rep['wechat'].append({
80
+ 'account': acct, 'file': os.path.basename(p), 'bytes': size,
81
+ 'encrypted': not is_plain_sqlite(p),
82
+ 'mtime': time.strftime('%Y-%m-%d', time.localtime(mtime)),
83
+ 'path': p,
84
+ })
85
+ # 媒体目录
86
+ for mdir in SIDECAR_MEDIA:
87
+ mp = os.path.join(acc_dir, mdir)
88
+ if os.path.isdir(mp):
89
+ total = 0
90
+ cnt = 0
91
+ for dp, _d, fs in os.walk(mp):
92
+ for fn in fs:
93
+ try:
94
+ total += os.path.getsize(os.path.join(dp, fn))
95
+ cnt += 1
96
+ except OSError:
97
+ pass
98
+ if cnt:
99
+ rep['media'].append({'platform': 'wechat', 'account': acct, 'dir': mdir,
100
+ 'files': cnt, 'bytes': total})
101
+ for root in QQ_ROOTS:
102
+ if not os.path.isdir(root):
103
+ continue
104
+ for acct in sorted(os.listdir(root)):
105
+ acc_dir = os.path.join(root, acct)
106
+ if not os.path.isdir(acc_dir):
107
+ continue
108
+ dbs = walk(os.path.join(acc_dir, 'nt_qq', 'nt_db')) if os.path.isdir(os.path.join(acc_dir, 'nt_qq', 'nt_db')) else []
109
+ for p, size, mtime in sorted(dbs, key=lambda x: -x[1])[:10]:
110
+ rep['qq'].append({'account': acct, 'file': os.path.basename(p), 'bytes': size,
111
+ 'encrypted': not is_plain_sqlite(p),
112
+ 'mtime': time.strftime('%Y-%m-%d', time.localtime(mtime)), 'path': p})
113
+ legacy = os.path.join(acc_dir, 'Msg3.0.db')
114
+ if os.path.isfile(legacy):
115
+ rep['qq'].append({'account': acct, 'file': 'Msg3.0.db', 'bytes': os.path.getsize(legacy),
116
+ 'encrypted': not is_plain_sqlite(legacy),
117
+ 'mtime': time.strftime('%Y-%m-%d', time.localtime(os.path.getmtime(legacy))),
118
+ 'path': legacy})
119
+ for mdir in ['Image', 'Video', 'Audio', 'FileRecv', 'nt_qq/nt_data/Emoji', 'nt_qq/nt_data/Pic']:
120
+ mp = os.path.join(acc_dir, mdir)
121
+ if os.path.isdir(mp):
122
+ total = cnt = 0
123
+ for dp, _d, fs in os.walk(mp):
124
+ for fn in fs:
125
+ try:
126
+ total += os.path.getsize(os.path.join(dp, fn)); cnt += 1
127
+ except OSError:
128
+ pass
129
+ if cnt:
130
+ rep['media'].append({'platform': 'qq', 'account': acct, 'dir': mdir, 'files': cnt, 'bytes': total})
131
+
132
+ db_bytes = sum(x['bytes'] for x in rep['wechat'] + rep['qq'])
133
+ media_bytes = sum(x['bytes'] for x in rep['media'])
134
+ # 解密速度按实测 4096B/页 × ~3000 页/s(Py 纯 CBC)≈ 12MB/s 估
135
+ decrypt_s = db_bytes / (12 * 1024 * 1024)
136
+ rep['summary'] = {
137
+ 'db_files': len(rep['wechat']) + len(rep['qq']),
138
+ 'db_bytes': db_bytes,
139
+ 'db_human': human(db_bytes),
140
+ 'media_files': sum(x['files'] for x in rep['media']),
141
+ 'media_bytes': media_bytes,
142
+ 'media_human': human(media_bytes),
143
+ 'est_decrypt_sec': round(decrypt_s, 1),
144
+ 'est_decrypt_human': f'{decrypt_s/60:.1f} 分钟',
145
+ 'encrypted_db': sum(1 for x in rep['wechat'] + rep['qq'] if x['encrypted']),
146
+ }
147
+ return rep
148
+
149
+
150
+ def main():
151
+ ap = argparse.ArgumentParser()
152
+ ap.add_argument('--json', action='store_true')
153
+ a = ap.parse_args()
154
+ r = inventory()
155
+ out = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))),
156
+ 'out', 'chat-archive', 'inventory-%s.json' % time.strftime('%Y%m%d-%H%M%S'))
157
+ os.makedirs(os.path.dirname(out), exist_ok=True)
158
+ json.dump(r, open(out, 'w', encoding='utf-8'), ensure_ascii=False, indent=2)
159
+ if a.json:
160
+ print(json.dumps(r, ensure_ascii=False, indent=2)); return
161
+ print('=' * 74)
162
+ print('本机聊天数据盘点 ' + r['at'])
163
+ print('=' * 74)
164
+ for plat, rows, title in (('wechat', r['wechat'], '微信 4.x'), ('qq', r['qq'], 'QQ NT')):
165
+ print(f'\n— {title} —')
166
+ for x in rows:
167
+ print(f" {human(x['bytes']):>9} {x['mtime']} {'🔒加密' if x['encrypted'] else '明文'} "
168
+ f"{x['account']}/{x['file']}")
169
+ if r['media']:
170
+ print('\n— 媒体(图片/视频/语音/文件)—')
171
+ for m in sorted(r['media'], key=lambda x: -x['bytes'])[:12]:
172
+ print(f" {human(m['bytes']):>9} {m['files']:>7} 个 {m['platform']}/{m['account']}/{m['dir']}")
173
+ s = r['summary']
174
+ print('\n— 汇总 —')
175
+ print(f" 数据库 {s['db_files']} 个 / {s['db_human']}(其中加密 {s['encrypted_db']} 个)")
176
+ print(f" 媒体 {s['media_files']} 个 / {s['media_human']}")
177
+ print(f" 纯解密耗时估算(12MB/s):{s['est_decrypt_human']}")
178
+ print(f'\n清单已写入: {out}')
179
+
180
+
181
+ if __name__ == '__main__':
182
+ main()
@@ -0,0 +1,114 @@
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ merge-sft.py — 把多路 SFT 产物合成一份最终训练集(本地、离线、可重复)
5
+
6
+ 为什么要合并而不是直接 concat:
7
+ 爸爸/妈妈/群聊三路各自独立生成,同一段对话会被不同 ctx 长度反复切片,
8
+ 直接拼会重复刷同一条样本 — 小模型最容易被这种重复带成复读机。
9
+ 这里按「用户侧末句 + 助手回复」的归一化指纹去重,并保留来源统计,
10
+ 方便训练时按 source 做采样权重。
11
+
12
+ 用法:
13
+ python scripts/chat-archive/merge-sft.py --train archive/sft3/private/mix.train.jsonl --train archive/sft3/bot/mom.train.jsonl \
14
+ --val archive/sft3/private/mix.val.jsonl --val archive/sft3/bot/mom.val.jsonl \
15
+ --out archive/sft3/final
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import argparse
20
+ import hashlib
21
+ import json
22
+ import os
23
+ import re
24
+ import time
25
+
26
+
27
+ def norm(s: str) -> str:
28
+ return re.sub(r'[\s\u3000,。!?、;:""''()()\[\]{}~~…—\-]+', '', str(s or '')).lower()
29
+
30
+
31
+ def fingerprint(row: dict) -> str:
32
+ msgs = row.get('messages') or []
33
+ user = next((m.get('content', '') for m in reversed(msgs) if m.get('role') == 'user'), '')
34
+ asst = next((m.get('content', '') for m in reversed(msgs) if m.get('role') == 'assistant'), '')
35
+ raw = norm(user)[-80:] + '|' + norm(asst)
36
+ return hashlib.sha1(raw.encode('utf-8')).hexdigest()
37
+
38
+
39
+ def load(paths: list[str]) -> list[dict]:
40
+ out = []
41
+ for p in paths:
42
+ if not p or not os.path.exists(p):
43
+ print(f' [跳过] 不存在:{p}')
44
+ continue
45
+ with open(p, encoding='utf-8', errors='ignore') as f:
46
+ for line in f:
47
+ line = line.strip()
48
+ if not line:
49
+ continue
50
+ try:
51
+ j = json.loads(line)
52
+ except Exception:
53
+ continue
54
+ if not (j.get('messages') and len(j['messages']) >= 2):
55
+ continue
56
+ out.append(j)
57
+ return out
58
+
59
+
60
+ def dedupe(rows: list[dict]) -> tuple[list[dict], int]:
61
+ seen = set()
62
+ kept = []
63
+ for r in rows:
64
+ fp = fingerprint(r)
65
+ if fp in seen:
66
+ continue
67
+ seen.add(fp)
68
+ kept.append(r)
69
+ return kept, len(rows) - len(kept)
70
+
71
+
72
+ def main():
73
+ ap = argparse.ArgumentParser()
74
+ ap.add_argument('--train', action='append', default=[])
75
+ ap.add_argument('--val', action='append', default=[])
76
+ ap.add_argument('--out', default='archive/sft3/final')
77
+ a = ap.parse_args()
78
+
79
+ train = load(a.train)
80
+ val = load(a.val)
81
+ print(f'读入 train={len(train)} val={len(val)}')
82
+ train, dup_t = dedupe(train)
83
+ val, dup_v = dedupe(val)
84
+ # 验证集不能和训练集重复:拿 train 的指纹把 val 里的漏网者剔掉
85
+ tfp = {fingerprint(r) for r in train}
86
+ val = [r for r in val if fingerprint(r) not in tfp]
87
+ print(f'去重后 train={len(train)}(去掉重复 {dup_t}) val={len(val)}(去掉重复 {dup_v + 0})')
88
+
89
+ os.makedirs(a.out, exist_ok=True)
90
+ for name, rows in (('train', train), ('val', val)):
91
+ p = os.path.join(a.out, f'{name}.jsonl')
92
+ with open(p, 'w', encoding='utf-8') as f:
93
+ for r in rows:
94
+ f.write(json.dumps(r, ensure_ascii=False) + '\n')
95
+ print(f' {name}: {len(rows)} → {p}')
96
+
97
+ src = {}
98
+ for r in train:
99
+ s = str((r.get('meta') or {}).get('source') or 'unknown')
100
+ src[s] = src.get(s, 0) + 1
101
+ stats = {
102
+ 'at': time.strftime('%Y-%m-%d %H:%M:%S'),
103
+ 'train': len(train), 'val': len(val),
104
+ 'deduped_train': dup_t, 'by_source': src,
105
+ 'avg_reply_chars': round(sum(len(r['messages'][-1]['content']) for r in train) / max(1, len(train)), 1),
106
+ }
107
+ with open(os.path.join(a.out, 'stats.json'), 'w', encoding='utf-8') as f:
108
+ json.dump(stats, f, ensure_ascii=False, indent=2)
109
+ print(json.dumps(stats, ensure_ascii=False, indent=2))
110
+ return 0
111
+
112
+
113
+ if __name__ == '__main__':
114
+ raise SystemExit(main())
@@ -0,0 +1,217 @@
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ qce-pull.py — 从本机 QQ Chat Exporter(NapCat Framework)拉一个会话的全部历史文字
5
+
6
+ 为什么不用它的「导出任务」:实测长会话导出会卡在 55% 不动(卡在资源下载/打包)。
7
+ 这里改走 /api/messages/fetch 分页接口,按月切时间窗(接口单次总数上限 5000),
8
+ 自己去重、自己落盘,纯文字、可断点续跑。
9
+
10
+ 用法:
11
+ python scripts/chat-archive/qce-pull.py --peer-uid u_xxx --peer-uin 2905608061 \
12
+ --name 启星 --out f:/qqbot/archive/chat/qq-qixing
13
+
14
+ 产物:
15
+ <out>/messages.jsonl 一条消息一行(含 text / time / sender / type)
16
+ <out>/chat.txt 人读版:2024-01-02 03:04 木囿: 内容
17
+ <out>/state.json 已拉完的月份(断点续跑)
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import argparse
22
+ import json
23
+ import os
24
+ import sys
25
+ import time
26
+ import urllib.request
27
+ from datetime import datetime, timedelta, timezone
28
+
29
+ BASE = 'http://127.0.0.1:40653'
30
+ TZ = timezone.utc
31
+
32
+
33
+ def post(path, payload, token, timeout=60):
34
+ req = urllib.request.Request(
35
+ BASE + path,
36
+ data=json.dumps(payload).encode(),
37
+ headers={'content-type': 'application/json', 'authorization': 'Bearer ' + token},
38
+ method='POST',
39
+ )
40
+ with urllib.request.urlopen(req, timeout=timeout) as r:
41
+ return json.loads(r.read().decode('utf-8', 'ignore'))
42
+
43
+
44
+ def elem_text(el):
45
+ """把 elements 里能读的文字/占位提出来"""
46
+ if not isinstance(el, dict):
47
+ return ''
48
+ t = el.get('textElement')
49
+ if t and t.get('content'):
50
+ return str(t['content'])
51
+ if el.get('faceElement'):
52
+ return '[表情]'
53
+ if el.get('marketFaceElement'):
54
+ return '[表情包]'
55
+ if el.get('picElement'):
56
+ return '[图片]'
57
+ if el.get('pttElement'):
58
+ return '[语音]'
59
+ if el.get('videoElement'):
60
+ return '[视频]'
61
+ if el.get('fileElement'):
62
+ return '[文件]'
63
+ if el.get('replyElement'):
64
+ return '[回复]'
65
+ if el.get('arkElement') or el.get('structElement'):
66
+ return '[卡片]'
67
+ return ''
68
+
69
+
70
+ def msg_text(m):
71
+ parts = []
72
+ for el in (m.get('elements') or []):
73
+ s = elem_text(el)
74
+ if s:
75
+ parts.append(s)
76
+ return ''.join(parts).strip()
77
+
78
+
79
+ def fmt_time(ts):
80
+ try:
81
+ return datetime.fromtimestamp(int(ts), TZ).astimezone().strftime('%Y-%m-%d %H:%M:%S')
82
+ except Exception:
83
+ return str(ts)
84
+
85
+
86
+ def chunk_windows(start_year=2022, start_month=1, days=5):
87
+ """按 5 天切片。
88
+
89
+ 为什么不用整月:实测 /api/messages/fetch 单次查询只回 400 条左右
90
+ (2026-11 实际 488 条,整月窗口只拿到 400;换成 limit=100 又只回 100 条),
91
+ 所以靠**时间切片**把每次查询压到 400 条以内,才拿得全。
92
+ """
93
+ now = datetime.now()
94
+ cur = datetime(start_year, start_month, 1)
95
+ while cur <= now:
96
+ nxt = cur + timedelta(days=days)
97
+ yield (cur.strftime('%Y-%m-%d'),
98
+ int(cur.timestamp() * 1000),
99
+ int((nxt - timedelta(milliseconds=1)).timestamp() * 1000))
100
+ cur = nxt
101
+
102
+
103
+ def fetch_window(peer, a, b, token, limit=100):
104
+ out, page = [], 1
105
+ while True:
106
+ j = post('/api/messages/fetch',
107
+ {'peer': peer, 'page': page, 'limit': limit,
108
+ 'filter': {'startTime': a, 'endTime': b}}, token)
109
+ if not j.get('success'):
110
+ raise RuntimeError('fetch failed: %s' % j.get('error'))
111
+ d = j['data']
112
+ got = d.get('messages') or []
113
+ out.extend(got)
114
+ # 不能信 hasNext:实测 total=203 时第 2 页就返回 hasNext=false,会少 3 条。
115
+ # 只有「不满一页 / 空页」才是真的到底。
116
+ if len(got) < limit or not got:
117
+ break
118
+ page += 1
119
+ if page > 40: # 单窗口最多 4000 条
120
+ break
121
+ time.sleep(0.12)
122
+ return out
123
+
124
+
125
+ CAP = 400 # 接口单次查询实测只回 400 条(2026-11 实际 488 条,只拿到 400)
126
+
127
+
128
+ def gather(peer, a, b, token, depth=0):
129
+ """拉一个时间窗;命中 400 上限就二分时间,避免静默截断"""
130
+ msgs = fetch_window(peer, a, b, token)
131
+ if len(msgs) >= CAP and depth < 6 and (b - a) > 2 * 86400000:
132
+ mid = (a + b) // 2
133
+ return gather(peer, a, mid, token, depth + 1) + gather(peer, mid + 1, b, token, depth + 1)
134
+ return msgs
135
+
136
+
137
+ def main():
138
+ ap = argparse.ArgumentParser()
139
+ ap.add_argument('--token', required=True)
140
+ ap.add_argument('--peer-uid', required=True)
141
+ ap.add_argument('--peer-uin', default='')
142
+ ap.add_argument('--name', default='')
143
+ ap.add_argument('--out', required=True)
144
+ ap.add_argument('--from-year', type=int, default=2022)
145
+ ap.add_argument('--from-month', type=int, default=1)
146
+ ap.add_argument('--force-from', default='', help='从某月(YYYY-MM)起重拉,忽略断点(用来自动补截断的月份)')
147
+ a = ap.parse_args()
148
+
149
+ os.makedirs(a.out, exist_ok=True)
150
+ db = os.path.join(a.out, 'messages.jsonl')
151
+ st = os.path.join(a.out, 'state.json')
152
+ seen = set()
153
+ if os.path.exists(db):
154
+ with open(db, encoding='utf-8') as f:
155
+ for line in f:
156
+ try:
157
+ seen.add(json.loads(line)['id'])
158
+ except Exception:
159
+ pass
160
+ done = set()
161
+ if os.path.exists(st):
162
+ try:
163
+ done = set(json.load(open(st, encoding='utf-8')).get('months') or [])
164
+ except Exception:
165
+ done = set()
166
+
167
+ peer = {'chatType': 1, 'peerUid': a.peer_uid, 'peerUin': a.peer_uin, 'name': a.name}
168
+ total_new = 0
169
+ for key, s, e in chunk_windows(a.from_year, a.from_month):
170
+ if key in done and not (a.force_from and key >= a.force_from):
171
+ continue
172
+ msgs = gather(peer, s, e, a.token)
173
+ fresh = []
174
+ for m in msgs:
175
+ mid = str(m.get('msgId') or '')
176
+ if not mid or mid in seen:
177
+ continue
178
+ txt = msg_text(m)
179
+ seen.add(mid)
180
+ fresh.append({
181
+ 'id': mid,
182
+ 'time': int(m.get('msgTime') or 0),
183
+ 'time_str': fmt_time(m.get('msgTime')),
184
+ 'sender': m.get('sendNickName') or '',
185
+ 'sender_uid': m.get('senderUid') or '',
186
+ 'type': int(m.get('msgType') or 0),
187
+ 'text': txt,
188
+ })
189
+ fresh.sort(key=lambda x: x['time'])
190
+ if fresh:
191
+ with open(db, 'a', encoding='utf-8') as f:
192
+ for r in fresh:
193
+ f.write(json.dumps(r, ensure_ascii=False) + '\n')
194
+ total_new += len(fresh)
195
+ done.add(key)
196
+ json.dump({'months': sorted(done)}, open(st, 'w', encoding='utf-8'), ensure_ascii=False)
197
+ print('%s: +%d (本月 %d 条, 累计新增 %d)' % (key, len(fresh), len(msgs), total_new), flush=True)
198
+
199
+ # 出人读版
200
+ rows = []
201
+ with open(db, encoding='utf-8') as f:
202
+ for line in f:
203
+ try:
204
+ r = json.loads(line)
205
+ except Exception:
206
+ continue
207
+ if r.get('text'):
208
+ rows.append(r)
209
+ rows.sort(key=lambda x: x['time'])
210
+ with open(os.path.join(a.out, 'chat.txt'), 'w', encoding='utf-8') as f:
211
+ for r in rows:
212
+ f.write('%s %s: %s\n' % (r.get('time_str'), r.get('sender'), r['text']))
213
+ print('done: %d 条有文字的消息 -> %s/chat.txt' % (len(rows), a.out), flush=True)
214
+
215
+
216
+ if __name__ == '__main__':
217
+ sys.exit(main())