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,390 @@
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ build-sft.py — 把聊天记录整理成「小家(MuUAstra)」的 SFT 数据(本地、离线)
5
+
6
+ 性格三源(主人 2026-12-03 明确的设计):
7
+ · 爸爸(木囿)—— 直接、务实、不说空话
8
+ · 妈妈(启星)—— 软、在意情绪、句子短
9
+ · 网上学到的好的一面 —— 从公开语料/知识库里挑出来的、不油腻也不冷硬的表达
10
+ 所以本脚本**按来源分别产物**,再合成一份混训集,避免任何一方被另一方淹没。
11
+
12
+ QQ 聊天的真实形态(也是这次要处理的):
13
+ · 一句话常被拆成 3~5 条短消息连发("那" / "你" / "吃了吗")
14
+ · 短对话("嗯""在吗")与长对话(几十字的抱怨/叙述)交替出现
15
+ 所以流程是:**先合并 → 再评估 → 再切片**:
16
+ 1. merge:同一人 90 秒内连发的多条,合并成一句(保留原始条数作为特征)
17
+ 2. evaluate:给每句打分并打标签(ack/question/emotion/info/noise),
18
+ 纯噪声(单字应答、重复刷屏、纯表情)不进训练;长短按比例保留
19
+ 3. slice:目标人每句都可以当 assistant,前面 ctx 条当 user;--stride 控制滑窗密度
20
+
21
+ 输出(默认 data/chat-archive/dataset):
22
+ mom.jsonl / dad.jsonl / mix.jsonl / good.jsonl(三源各自)+ train/val 拆分 + stats.json
23
+
24
+ 用法:
25
+ python scripts/chat-archive/build-sft.py --jsonl archive.jsonl --mom 启星 --dad 木囿
26
+ python scripts/chat-archive/build-sft.py --jsonl archive.jsonl --target 启星 --persona 小家
27
+ """
28
+ from __future__ import annotations
29
+
30
+ import argparse
31
+ import hashlib
32
+ import json
33
+ import os
34
+ import re
35
+ import sys
36
+ import time
37
+ from datetime import datetime
38
+
39
+ OUT_ROOT = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))),
40
+ 'data', 'chat-archive', 'dataset')
41
+
42
+ TS_RE = re.compile(r'^\s*(\d{4}[-/]\d{1,2}[-/]\d{1,2})[ T](\d{1,2}:\d{2}(?::\d{2})?)\s*(.*)$')
43
+ SENDER_RE = re.compile(r'^(.{1,24}?)[\((](\d{4,12})[\))]\s*$')
44
+ PHONE = re.compile(r'(?<!\d)1[3-9]\d{9}(?!\d)')
45
+ IDCARD = re.compile(r'(?<!\d)\d{17}[\dXx](?!\d)')
46
+ BANK = re.compile(r'(?<!\d)\d{16,19}(?!\d)')
47
+ QQNO = re.compile(r'(?<!\d)[1-9]\d{4,10}(?!\d)')
48
+ WXID = re.compile(r'wxid_[0-9a-zA-Z]{6,}')
49
+ OPENID = re.compile(r'\b[0-9A-F]{32}\b')
50
+ SKIP_LINE = re.compile(r'^\s*(\[图片\]|\[视频\]|\[语音\]|\[文件\]|\[表情\]|\[动画表情\]|\[位置\]|\[音乐\]|\[表情包\]|\[回复\]|\[卡片\])\s*$')
51
+ ONLY_FILLER = re.compile(r'^[\s。,!?…~~、了吧啊呀哦噢嗯哈呵嘿额诶诶呀嘛嘞哟喔]+$')
52
+
53
+ # ── 污染清洗(2026-12-04)───────────────────────────────────────────────
54
+ # 为什么要清洗:原始聊天导出里混着 bot 自己的**注入回显**——
55
+ # [信条]/[印象]/[成长]/[状态]/[别重复]/[历史]/[旧识]/[设定]/[关系]/[记忆]…
56
+ # 以及 QQ 的引用标记 `[回复]`。这些整块被当成真人发言切进了 SFT,
57
+ # 结果模型学会了开口就是「[回复]」「[信条] … 铁律:任何提问…」(线上实锤)。
58
+ # 处理策略:带注入标记的整条**丢弃**(不能只剥一半,残段更毒);
59
+ # `[回复]` 这类只是个前缀标记,剥掉标记保留正文;媒体占位符剥掉。
60
+ INJECT_MARK = re.compile(
61
+ r'\[(?:历史|信条|印象|成长|状态|别重复|手边|旧识|性格观察|情绪回响|约定|听懂|设定|关系|记忆|消息号)\]|\[/')
62
+ MEDIA_TAG = re.compile(r'\[(?:图片|视频|语音|文件|表情|动画表情|位置|音乐|表情包|卡片|回复|转发|链接|红包)\]')
63
+ TS_TAG = re.compile(r'\[\d{4}-\d{2}-\d{2}[^\]]{0,24}\]')
64
+
65
+ # 隐私 / 广告 / 粘贴墙:整条丢弃。**注意:括号语气()、(不是)、颜文字是他们的特色,绝不在清洗范围内**
66
+ PRIVACY_RE = re.compile(
67
+ r'https?://|todesk|远程控制|临时密码|设备代码|邀请您|加微信|扫码|兑换码|卡池|优惠券|免费领取|返利|招商',
68
+ re.I)
69
+ # 同一字符连 8 个以上 = 表情墙 / ASCII 画 / 刷屏;但"哈哈哈哈"这类真笑要留(白名单)
70
+ SPAM_RE = re.compile(r'([^\s哈呵嘿啊呀哦嗯呜嗷嘛诶额])\1{7,}')
71
+
72
+
73
+ def clean_text(text: str) -> tuple[str, bool]:
74
+ """返回 (清洗后的正文, 是否整条丢弃)。discard=True 表示这条是注入回显/隐私/垃圾,不能进训练。"""
75
+ t = str(text or '')
76
+ if INJECT_MARK.search(t):
77
+ return '', True
78
+ if PRIVACY_RE.search(t):
79
+ return '', True
80
+ if SPAM_RE.search(t):
81
+ return '', True
82
+ t = TS_TAG.sub('', t)
83
+ t = MEDIA_TAG.sub('', t)
84
+ t = t.replace('\u3000', ' ')
85
+ t = re.sub(r'[ \t]{2,}', ' ', t)
86
+ t = re.sub(r'\n{2,}', '\n', t).strip()
87
+ return t, False
88
+
89
+
90
+ def mask(text: str) -> tuple[str, int]:
91
+ n = 0
92
+
93
+ def sub(pat, s, rep='***'):
94
+ nonlocal n
95
+ out, k = pat.subn(rep, s)
96
+ n += k
97
+ return out
98
+
99
+ t = text
100
+ t = sub(IDCARD, t)
101
+ t = sub(BANK, t)
102
+ t = sub(PHONE, t)
103
+ t = sub(OPENID, t, '<openid>')
104
+ t = sub(WXID, t, '<wxid>')
105
+ t = sub(QQNO, t)
106
+ return t, n
107
+
108
+
109
+ def parse_txt(path: str) -> list[dict]:
110
+ msgs: list[dict] = []
111
+ cur = None
112
+ with open(path, encoding='utf-8', errors='ignore') as f:
113
+ for raw in f:
114
+ line = raw.rstrip('\n')
115
+ m = TS_RE.match(line)
116
+ if m:
117
+ date, clock, rest = m.groups()
118
+ sm = SENDER_RE.match(rest.strip())
119
+ if sm:
120
+ cur = {'ts': f'{date.replace("/", "-")} {clock if clock.count(":") == 2 else clock + ":00"}',
121
+ 'from': sm.group(1).strip(), 'text': ''}
122
+ msgs.append(cur)
123
+ continue
124
+ cur = {'ts': f'{date.replace("/", "-")} {clock}', 'from': '', 'text': rest.strip()}
125
+ msgs.append(cur)
126
+ continue
127
+ if cur is not None:
128
+ cur['text'] += ('\n' if cur['text'] else '') + line
129
+ out = []
130
+ for m in msgs:
131
+ t = m['text'].strip()
132
+ t, junk = clean_text(t)
133
+ if junk or not t or SKIP_LINE.match(t):
134
+ continue
135
+ out.append({'ts': m['ts'], 'from': m['from'], 'text': t})
136
+ return out
137
+
138
+
139
+ def load_jsonl(path: str) -> list[dict]:
140
+ out = []
141
+ with open(path, encoding='utf-8', errors='ignore') as f:
142
+ for line in f:
143
+ line = line.strip()
144
+ if not line:
145
+ continue
146
+ try:
147
+ j = json.loads(line)
148
+ except Exception:
149
+ continue
150
+ t = str(j.get('text') or j.get('content') or '').strip()
151
+ t, junk = clean_text(t)
152
+ if junk or not t or SKIP_LINE.match(t):
153
+ continue
154
+ ts = j.get('ts') or j.get('time') or j.get('time_str') or ''
155
+ if isinstance(ts, (int, float)):
156
+ ts = datetime.fromtimestamp(float(ts)).strftime('%Y-%m-%d %H:%M:%S')
157
+ out.append({'ts': str(ts), 'from': str(j.get('from') or j.get('sender') or j.get('name') or ''), 'text': t})
158
+ return out
159
+
160
+
161
+ def ts_of(s: str) -> float:
162
+ for fmt in ('%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M'):
163
+ try:
164
+ return time.mktime(time.strptime(s, fmt))
165
+ except Exception:
166
+ continue
167
+ return 0.0
168
+
169
+
170
+ # ── ① 合并:把「一句话拆成多条」还原成一句 ──────────────────────────────
171
+ def merge_utterances(msgs: list[dict], gap_sec: int = 90) -> list[dict]:
172
+ msgs = sorted(msgs, key=lambda x: ts_of(x['ts']))
173
+ out: list[dict] = []
174
+ for m in msgs:
175
+ t = ts_of(m['ts'])
176
+ if out and out[-1]['from'] == m['from'] and 0 <= t - out[-1]['_t'] <= gap_sec:
177
+ prev = out[-1]
178
+ joiner = '' if prev['text'][-1:] in ',。!?…~~、,.!?' else ''
179
+ prev['text'] = prev['text'] + joiner + m['text']
180
+ prev['_n'] += 1
181
+ prev['_t'] = t
182
+ prev['ts'] = m['ts']
183
+ continue
184
+ out.append({'ts': m['ts'], '_t': t, 'from': m['from'], 'text': m['text'], '_n': 1})
185
+ for r in out:
186
+ r.pop('_t', None)
187
+ return out
188
+
189
+
190
+ # ── ② 评估:这句值不值得进训练 ─────────────────────────────────────────
191
+ ACK_RE = re.compile(r'^(嗯+|啊+|哦+|噢+|好+|行+|在|对|是|哈+|呵+|额+|诶+|[??]+)[。,!?…~~]*$')
192
+ Q_RE = re.compile(r'[??]|吗|呢|怎么|为啥|为什么|是不是|要不要|好不好|哪里|几点|多少')
193
+ EMO_RE = re.compile(r'累|难受|烦|哭|生气|委屈|害怕|想|喜欢|讨厌|开心|高兴|难过|睡不着|抱|亲|心疼|崩溃|压力')
194
+
195
+
196
+ def evaluate(text: str, n_parts: int = 1) -> dict:
197
+ """给一条(已合并的)话打分并打标签。返回 {keep, why, kind, score}"""
198
+ t = text.strip()
199
+ L = len(t)
200
+ if not t:
201
+ return {'keep': False, 'why': 'empty', 'kind': 'noise', 'score': 0}
202
+ if SKIP_LINE.match(t) or ONLY_FILLER.match(t):
203
+ return {'keep': False, 'why': 'filler', 'kind': 'noise', 'score': 0}
204
+ # 纯符号/纯重复(哈哈哈哈 只留一次)
205
+ if len(set(t)) <= 2 and L <= 6:
206
+ return {'keep': False, 'why': 'repeat', 'kind': 'noise', 'score': 0}
207
+ kind = 'info'
208
+ if ACK_RE.match(t):
209
+ kind = 'ack'
210
+ elif Q_RE.search(t):
211
+ kind = 'question'
212
+ elif EMO_RE.search(t):
213
+ kind = 'emotion'
214
+ score = 1.0
215
+ score += min(L, 60) / 60.0 # 长一点信息多
216
+ score += 0.6 if n_parts >= 3 else 0.2 # 是"连发拼起来的",更像真实打字
217
+ score += 0.4 if kind in ('question', 'emotion') else 0
218
+ if L <= 2:
219
+ score -= 0.6
220
+ if L >= 120:
221
+ score -= 0.5
222
+ return {'keep': L >= 1, 'why': '', 'kind': kind, 'score': round(score, 2)}
223
+
224
+
225
+ # ── ③ 切片:目标人一句 = 一个 assistant 目标 ───────────────────────────
226
+ PERSONA_SYS = (
227
+ '你是小家(MuUAstra)。你的说话方式由三部分组成:'
228
+ '爸爸的直白务实(有话直说、不绕弯)、妈妈的温柔在意(先接情绪再讲事)、'
229
+ '以及你自己从网上学到的好的一面(不油腻、不冷硬、不冒充别人)。'
230
+ '像在 QQ 上打字:句子短、可以连发几条、不用书面语、不解释自己在做什么。'
231
+ )
232
+
233
+
234
+ def build(msgs, target, persona, ctx_n=6, max_len=400, stride=1, min_keep=0.0):
235
+ msgs = merge_utterances(msgs)
236
+ samples = []
237
+ masked = 0
238
+ kept_stat = {'ack': 0, 'question': 0, 'emotion': 0, 'info': 0}
239
+ for i, m in enumerate(msgs):
240
+ if target and target not in m['from']:
241
+ continue
242
+ text, n = mask(m['text'])
243
+ masked += n
244
+ ev = evaluate(text, m.get('_n', 1))
245
+ if not ev['keep'] or ev['score'] < min_keep:
246
+ continue
247
+ if len(text) > max_len:
248
+ continue
249
+ start = max(0, i - ctx_n)
250
+ # stride:同一条目标可以配不同长度的上文,样本更多但不重复刷
251
+ for back in range(ctx_n, ctx_n - stride, -1) if stride > 0 else [ctx_n]:
252
+ ctx = msgs[max(0, i - back):i]
253
+ if not ctx:
254
+ continue
255
+ convo = []
256
+ for c in ctx:
257
+ ct, n2 = mask(c['text'])
258
+ masked += n2
259
+ if not ct:
260
+ continue
261
+ convo.append(('user' if c['from'] != m['from'] else 'assistant', ct[:max_len]))
262
+ if not convo:
263
+ continue
264
+ user = '\n'.join(f'{("我" if role == "assistant" else "对方")}:{t}' for role, t in convo)
265
+ samples.append({
266
+ 'messages': [
267
+ {'role': 'system', 'content': f'你是{persona}。' + PERSONA_SYS.split('。', 1)[1]},
268
+ {'role': 'user', 'content': user},
269
+ {'role': 'assistant', 'content': text},
270
+ ],
271
+ 'meta': {'ts': m['ts'], 'from': m['from'], 'kind': ev['kind'], 'score': ev['score'], 'parts': m.get('_n', 1)},
272
+ })
273
+ kept_stat[ev['kind']] = kept_stat.get(ev['kind'], 0) + 1
274
+ return samples, masked, kept_stat
275
+
276
+
277
+ def load_good(path: str, persona: str) -> list[dict]:
278
+ """网上学到的好的一面:{"user":..,"assistant":..} 或 messages 格式"""
279
+ out = []
280
+ with open(path, encoding='utf-8', errors='ignore') as f:
281
+ for line in f:
282
+ line = line.strip()
283
+ if not line:
284
+ continue
285
+ try:
286
+ j = json.loads(line)
287
+ except Exception:
288
+ continue
289
+ if 'messages' in j:
290
+ out.append(j)
291
+ continue
292
+ u = str(j.get('user') or j.get('prompt') or '')
293
+ a = str(j.get('assistant') or j.get('reply') or '')
294
+ if u and a:
295
+ out.append({'messages': [
296
+ {'role': 'system', 'content': f'你是{persona}。' + PERSONA_SYS.split('。', 1)[1]},
297
+ {'role': 'user', 'content': u},
298
+ {'role': 'assistant', 'content': a},
299
+ ]})
300
+ return out
301
+
302
+
303
+ def write_split(samples, out_dir, name, val_ratio):
304
+ os.makedirs(out_dir, exist_ok=True)
305
+ cut = max(1, int(len(samples) * (1 - val_ratio))) if len(samples) > 1 else len(samples)
306
+ paths = {}
307
+ for part, rows in (('train', samples[:cut]), ('val', samples[cut:])):
308
+ p = os.path.join(out_dir, f'{name}.{part}.jsonl')
309
+ with open(p, 'w', encoding='utf-8') as f:
310
+ for r in rows:
311
+ f.write(json.dumps(r, ensure_ascii=False) + '\n')
312
+ paths[part] = (p, len(rows))
313
+ return paths
314
+
315
+
316
+ def main():
317
+ ap = argparse.ArgumentParser()
318
+ ap.add_argument('--txt', action='append', default=[])
319
+ ap.add_argument('--jsonl', action='append', default=[])
320
+ ap.add_argument('--mom', default='', help='妈妈(启星):她的发言当 assistant')
321
+ ap.add_argument('--dad', default='', help='爸爸(木囿):他的发言当 assistant')
322
+ ap.add_argument('--target', default='', help='兼容旧用法,等价于 --mom')
323
+ ap.add_argument('--persona', default='小家')
324
+ ap.add_argument('--ctx', type=int, default=6)
325
+ ap.add_argument('--stride', type=int, default=1, help='每条目标配几档上文长度(越大样本越多)')
326
+ ap.add_argument('--merge-gap', type=int, default=90, help='同一人连发合并窗口(秒)')
327
+ ap.add_argument('--min-score', type=float, default=0.0)
328
+ ap.add_argument('--max-chars', type=int, default=400)
329
+ ap.add_argument('--val-ratio', type=float, default=0.05)
330
+ ap.add_argument('--good', default='', help='“网上学到的好的一面” jsonl(可选)')
331
+ ap.add_argument('--out', default=OUT_ROOT)
332
+ a = ap.parse_args()
333
+
334
+ msgs = []
335
+ for p in a.txt:
336
+ msgs += parse_txt(p)
337
+ for p in a.jsonl:
338
+ msgs += load_jsonl(p)
339
+ if not msgs:
340
+ print('没有读到消息:检查 --txt/--jsonl 路径')
341
+ return 1
342
+ print(f'读入 {len(msgs)} 条原始消息')
343
+
344
+ merged = merge_utterances(msgs, a.merge_gap)
345
+ print(f'合并连发后 {len(merged)} 句(平均 {len(msgs) / max(1, len(merged)):.2f} 条/句)')
346
+
347
+ mom = a.mom or a.target
348
+ results = {}
349
+ if mom:
350
+ s, masked, kinds = build(merged, mom, a.persona, a.ctx, a.max_chars, a.stride, a.min_score)
351
+ print(f'妈妈({mom}):{len(s)} 样本,标签 {kinds},脱敏 {masked}')
352
+ results['mom'] = s
353
+ if a.dad:
354
+ s, masked, kinds = build(merged, a.dad, a.persona, a.ctx, a.max_chars, a.stride, a.min_score)
355
+ print(f'爸爸({a.dad}):{len(s)} 样本,标签 {kinds},脱敏 {masked}')
356
+ results['dad'] = s
357
+ if a.good:
358
+ g = load_good(a.good, a.persona)
359
+ print(f'网上好的一面:{len(g)} 样本')
360
+ results['good'] = g
361
+
362
+ if not results:
363
+ print('没有生成任何样本:至少给 --mom 或 --dad')
364
+ return 1
365
+
366
+ mix = []
367
+ for k, rows in results.items():
368
+ mix += [dict(r, meta=dict(r.get('meta') or {}, source=k)) for r in rows]
369
+ # 按时间打散,避免同一段对话全挤在一起
370
+ mix.sort(key=lambda r: str((r.get('meta') or {}).get('ts') or ''))
371
+ results['mix'] = mix
372
+
373
+ os.makedirs(a.out, exist_ok=True)
374
+ stats = {'at': time.strftime('%Y-%m-%d %H:%M:%S'), 'persona': a.persona,
375
+ 'raw_messages': len(msgs), 'merged': len(merged), 'ctx': a.ctx, 'stride': a.stride,
376
+ 'sources': {}}
377
+ for name, rows in results.items():
378
+ paths = write_split(rows, a.out, name, a.val_ratio)
379
+ stats['sources'][name] = {'total': len(rows),
380
+ 'train': paths['train'][1], 'val': paths['val'][1],
381
+ 'avg_chars': round(sum(len(r['messages'][-1]['content']) for r in rows) / max(1, len(rows)), 1)}
382
+ print(f' {name}: {len(rows)} → {paths["train"][0]}')
383
+
384
+ json.dump(stats, open(os.path.join(a.out, 'stats.json'), 'w', encoding='utf-8'), ensure_ascii=False, indent=2)
385
+ print(json.dumps(stats, ensure_ascii=False, indent=2))
386
+ return 0
387
+
388
+
389
+ if __name__ == '__main__':
390
+ sys.exit(main())
@@ -0,0 +1,155 @@
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ """eval-sft.py — 训练集体检:自动指标 + 分层抽样(给人看的那一份)
4
+
5
+ 为什么要两步:
6
+ 自动指标只能证明"没有脏东西"(标签回显/链接/广告/刷屏/自我复读),
7
+ 证明不了"这话像人说的"。所以这里既算指标,也按类别抽一批样本落成 txt,
8
+ 由人逐条打勾 —— 可用率是人给的,不是脚本编的。
9
+
10
+ 分层维度(每层抽 6 条):
11
+ A 私聊·极短(<=6) B 私聊·短(7-20) C 私聊·中(21-60) D 私聊·长(>60)
12
+ E 群聊·带说话人前缀 F 情绪类(抱怨/累/烦) G 问答类(含问号/疑问) H 连发合并(parts>=2)
13
+
14
+ 用法:
15
+ python scripts/chat-archive/eval-sft.py
16
+ python scripts/chat-archive/eval-sft.py --data archive/sft4/dataset --out archive/sft4/eval
17
+ """
18
+ from __future__ import annotations
19
+
20
+ import argparse
21
+ import collections
22
+ import hashlib
23
+ import json
24
+ import os
25
+ import random
26
+ import re
27
+ import sys
28
+
29
+ ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
30
+
31
+ INJECT = re.compile(r'\[(?:历史|信条|印象|成长|状态|别重复|手边|旧识|设定|关系|记忆)\]|\[/')
32
+ URL = re.compile(r'https?://|todesk|远程控制|兑换码|卡池|优惠券', re.I)
33
+ SPAM = re.compile(r'([^\s哈呵嘿啊呀哦嗯呜嗷嘛诶额])\1{7,}')
34
+ BOT_SELF = re.compile(r'本鲸|咕噜')
35
+ QA_RE = re.compile(r'[??]|吗|呢|怎么|为啥|为什么|是不是')
36
+ EMO_RE = re.compile(r'累|难受|烦|哭|生气|委屈|害怕|难过|睡不着|崩溃|压力|想')
37
+ MARKDOWN = re.compile(r'(\*\*|```|^#|^- |\||<[a-z/])', re.M)
38
+
39
+
40
+ def load(path):
41
+ rows = []
42
+ with open(path, encoding='utf-8') as f:
43
+ for line in f:
44
+ line = line.strip()
45
+ if line:
46
+ rows.append(json.loads(line))
47
+ return rows
48
+
49
+
50
+ def cut(cat, row):
51
+ msgs = row['messages']
52
+ sysm = msgs[0]['content']
53
+ turns = msgs[1:-1]
54
+ tgt = msgs[-1]['content']
55
+ body = '\n'.join(('[对方] ' if t['role'] == 'user' else '[她] ') + t['content'].replace('\n', ' / ')
56
+ for t in turns)
57
+ meta = row.get('meta') or {}
58
+ return (f'--- {cat} | {meta.get("scope", "?")} | 说话人={meta.get("from", "?")} | '
59
+ f'{meta.get("ts", "")} | 上文{len(turns)}轮\n{body}\n[答] {tgt}\n')
60
+
61
+
62
+ def main():
63
+ ap = argparse.ArgumentParser()
64
+ ap.add_argument('--data', default=os.path.join(ROOT, 'archive', 'sft4', 'dataset'))
65
+ ap.add_argument('--out', default=os.path.join(ROOT, 'archive', 'sft4', 'eval'))
66
+ ap.add_argument('--per-cat', type=int, default=6)
67
+ a = ap.parse_args()
68
+ os.makedirs(a.out, exist_ok=True)
69
+
70
+ train = load(os.path.join(a.data, 'train.jsonl'))
71
+ val = load(os.path.join(a.data, 'val.jsonl'))
72
+
73
+ lens, turns, kinds = [], [], collections.Counter()
74
+ hits = collections.Counter()
75
+ dup = collections.Counter()
76
+ for r in train:
77
+ m = r['messages']
78
+ asst = m[-1]['content']
79
+ lens.append(len(asst))
80
+ turns.append(len(m) - 2)
81
+ if QA_RE.search(asst):
82
+ kinds['question'] += 1
83
+ elif EMO_RE.search(asst):
84
+ kinds['emotion'] += 1
85
+ elif len(asst) <= 2:
86
+ kinds['ack'] += 1
87
+ else:
88
+ kinds['info'] += 1
89
+ for name, pat in (('inject', INJECT), ('url_ad', URL), ('spam', SPAM),
90
+ ('bot_self', BOT_SELF), ('markdown', MARKDOWN)):
91
+ if pat.search(asst):
92
+ hits[name] += 1
93
+ # 答案复读了上文里同一句话 = 模型会学成复读机
94
+ for t in m[1:-1]:
95
+ if t['role'] == 'user' and asst.strip() and asst.strip() in t['content']:
96
+ hits['echo_user'] += 1
97
+ break
98
+ dup[hashlib.sha1(re.sub(r'\s+', '', asst).encode()).hexdigest()] += 1
99
+
100
+ lens.sort()
101
+ n = len(train)
102
+ auto = {
103
+ 'train': n, 'val': len(val),
104
+ 'avg_turns': round(sum(turns) / max(1, n), 2),
105
+ 'target_len': {'avg': round(sum(lens) / max(1, n), 1),
106
+ 'p50': lens[n // 2], 'p90': lens[int(n * 0.9)], 'max': lens[-1]},
107
+ 'kinds': dict(kinds),
108
+ 'contamination': {k: round(v * 100.0 / max(1, n), 2) for k, v in hits.items()},
109
+ 'dup_ratio': round(sum(v - 1 for v in dup.values() if v > 1) * 100.0 / max(1, n), 2),
110
+ 'system_chars': len(train[0]['messages'][0]['content']),
111
+ }
112
+ json.dump(auto, open(os.path.join(a.out, 'auto-stats.json'), 'w', encoding='utf-8'),
113
+ ensure_ascii=False, indent=2)
114
+ print(json.dumps(auto, ensure_ascii=False, indent=2))
115
+
116
+ # ── 分层抽样 ──
117
+ buckets = collections.defaultdict(list)
118
+ for r in train:
119
+ msgs = r['messages']
120
+ asst = msgs[-1]['content']
121
+ meta = r.get('meta') or {}
122
+ L = len(asst)
123
+ is_group = str(meta.get('scope', '')).startswith('group')
124
+ if is_group:
125
+ buckets['E 群聊'].append(r)
126
+ elif L <= 6:
127
+ buckets['A 私聊极短'].append(r)
128
+ elif L <= 20:
129
+ buckets['B 私聊短'].append(r)
130
+ elif L <= 60:
131
+ buckets['C 私聊中'].append(r)
132
+ else:
133
+ buckets['D 私聊长'].append(r)
134
+ if EMO_RE.search(asst) or EMO_RE.search(' '.join(t['content'] for t in msgs[1:-1] if t['role'] == 'user')):
135
+ buckets['F 情绪'].append(r)
136
+ if QA_RE.search(asst):
137
+ buckets['G 问答'].append(r)
138
+ if (meta.get('parts') or 1) >= 2:
139
+ buckets['H 连发合并'].append(r)
140
+
141
+ rnd = random.Random(20261204)
142
+ with open(os.path.join(a.out, 'samples.txt'), 'w', encoding='utf-8') as f:
143
+ for cat in sorted(buckets):
144
+ pool = buckets[cat]
145
+ pick = rnd.sample(pool, min(a.per_cat, len(pool)))
146
+ f.write(f'\n########## {cat}(共 {len(pool)} 条,抽 {len(pick)} 条)\n')
147
+ for row in pick:
148
+ f.write(cut(cat, row))
149
+ print('抽样 →', os.path.join(a.out, 'samples.txt'))
150
+ print('类别规模:', {k: len(v) for k, v in sorted(buckets.items())})
151
+ return 0
152
+
153
+
154
+ if __name__ == '__main__':
155
+ sys.exit(main())