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.
- package/CHANGELOG.md +168 -154
- package/client/qqbot-settings.js +13401 -13380
- package/dist/config.js +573 -581
- package/dist/features/contextless-store.js +247 -247
- package/dist/features/four-source.js +338 -336
- package/dist/features/group-join-request.js +289 -287
- package/dist/features/local-models.js +1494 -1467
- package/dist/features/style-layer.js +501 -498
- package/dist/features/thinking-log.js +71 -69
- package/dist/gateway/bootstrap.js +1704 -1652
- package/dist/model/settings-reader.js +193 -102
- package/dist/shared/paths.js +128 -0
- package/dist/shared/settings-io.js +79 -83
- package/dshqqbot/.qqbot-extensions/inbound/00-vision.mjs +111 -0
- package/dshqqbot/.qqbot-extensions/inbound/aa-memory-recall.mjs +802 -794
- package/dshqqbot/.qqbot-extensions/inbound/az-feedback.mjs +113 -115
- package/dshqqbot/.qqbot-extensions/inbound/local-answer.mjs +689 -568
- package/dshqqbot/.qqbot-extensions/lib/local-llm.mjs +455 -444
- package/dshqqbot/.qqbot-extensions/lib/memory-agent.mjs +930 -928
- package/dshqqbot/.qqbot-extensions/lib/memory-core.mjs +537 -537
- package/dshqqbot/.qqbot-extensions/lib/memory-db.mjs +2476 -2245
- package/dshqqbot/.qqbot-extensions/lib/memory-hippo.mjs +18 -0
- package/dshqqbot/.qqbot-extensions/lib/memory.mjs +191 -186
- package/dshqqbot/.qqbot-extensions/lib/scope-util.mjs +84 -0
- package/dshqqbot/.qqbot-extensions/outbound/aa-sanitize.mjs +158 -154
- package/dshqqbot/.qqbot-extensions/outbound/memory-agent.mjs +121 -130
- package/dshqqbot/.qqbot-extensions/outbound/turn-memory.mjs +92 -101
- package/dshqqbot/.qqbot-extensions/tools/memory.mjs +178 -120
- package/dshqqbot/.qqbot-extensions/vendor/abogus/test-abogus.mjs +128 -126
- package/package.json +119 -118
- package/scripts/__pycache__/fan-mode.cpython-311.pyc +0 -0
- package/scripts/__pycache__/memory-audit.cpython-311.pyc +0 -0
- package/scripts/__pycache__/qq-ip-sync.cpython-311.pyc +0 -0
- package/scripts/__pycache__/qq-whitelist.cpython-311.pyc +0 -0
- package/scripts/ai-toolkit.py +607 -478
- package/scripts/chat-archive/__pycache__/build-sft-v4.cpython-311.pyc +0 -0
- package/scripts/chat-archive/__pycache__/build-sft.cpython-311.pyc +0 -0
- package/scripts/chat-archive/build-sft-v4.py +566 -0
- package/scripts/chat-archive/build-sft.py +390 -0
- package/scripts/chat-archive/eval-sft.py +155 -0
- package/scripts/chat-archive/extract-memory.py +143 -0
- package/scripts/chat-archive/inventory.py +182 -0
- package/scripts/chat-archive/merge-sft.py +114 -0
- package/scripts/chat-archive/qce-pull.py +217 -0
- package/scripts/chat-archive/qqheader.py +110 -0
- package/scripts/chat-archive/qqkey2.py +113 -0
- package/scripts/chat-archive/qqprobe.py +153 -0
- package/scripts/chat-archive/screen-collect.py +163 -0
- package/scripts/chat-archive/sqlcipher_probe.py +444 -0
- package/scripts/episode.py +529 -0
- package/scripts/fan-curve.py +218 -0
- package/scripts/fan-guard.cmd +8 -0
- package/scripts/fan-mode.py +380 -263
- package/scripts/gen-image.py +420 -413
- package/scripts/gen-video.py +186 -178
- package/scripts/hw-profile.py +175 -0
- package/scripts/media-enhance.py +402 -0
- package/scripts/memory-audit.py +581 -0
- package/scripts/migrate-scope.mjs +140 -139
- package/scripts/qq-connect-login.py +133 -0
- package/scripts/qq-ip-sync-hidden.vbs +5 -0
- package/scripts/qq-ip-sync.py +300 -0
- package/scripts/qq-whitelist.py +71 -0
- package/scripts/release-all.mjs +636 -509
- package/scripts/release-check.mjs +244 -226
- package/scripts/secure-room/index.html +334 -0
- package/scripts/secure-room/server.py +582 -0
- package/scripts/stickers/auto-tag.mjs +161 -0
- package/scripts/train/__pycache__/train-lora.cpython-311.pyc +0 -0
- package/scripts/train/gguf-quantize.py +92 -0
- package/scripts/train/gguf-to-hf.py +112 -0
- package/scripts/train/merge-lora.py +51 -0
- package/scripts/train/probe-mirrors.sh +12 -0
- package/scripts/train/probe-mirrors2.sh +20 -0
- package/scripts/train/setup-wsl.sh +23 -0
- package/scripts/train/setup-wsl2.sh +25 -0
- package/scripts/train/setup-wsl3.sh +22 -0
- package/scripts/train/setup-wsl4.sh +22 -0
- package/scripts/train/train-lora.py +319 -0
- package/dist/_backup_ctx_20261125_183653/dist/config.d.ts +0 -473
- package/dist/_backup_ctx_20261125_183653/dist/config.js +0 -450
- package/dist/_backup_ctx_20261125_183653/dist/features/contextless-trim.js +0 -304
- package/dist/_backup_ctx_20261125_183653/dist/session/session-manager.js +0 -1588
- package/dist/_backup_ctx_20261125_183653/dist/transport/inbound.js +0 -1567
- package/dist/_backup_ctx_20261125_183653/dist/transport/outbound.js +0 -647
- package/scripts/__pycache__/ai-mode.cpython-311.pyc +0 -0
- package/scripts/__pycache__/ai-toolkit.cpython-311.pyc +0 -0
- package/scripts/__pycache__/comfy_gen.cpython-311.pyc +0 -0
- package/scripts/__pycache__/gen-image.cpython-311.pyc +0 -0
- package/scripts/__pycache__/gen-video.cpython-311.pyc +0 -0
- package/scripts/__pycache__/model-registry.cpython-311.pyc +0 -0
- package/scripts/__pycache__/purge-standby.cpython-311.pyc +0 -0
|
Binary file
|
|
Binary file
|
|
@@ -0,0 +1,566 @@
|
|
|
1
|
+
#!/usr/bin/env python
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""build-sft-v4.py — 从「QQ 导出 + memory.db」生成原生多轮 SFT 数据(只读原始数据)
|
|
4
|
+
|
|
5
|
+
v3 的问题(这次要修的):
|
|
6
|
+
1. 上下文被拍平成一条 user 文本("对方:…\\n我:…"),和线上「一条消息进来」的形态
|
|
7
|
+
差得太远,模型学到的是"照着格式续写",不是"接话"。
|
|
8
|
+
2. 群里把机器人自己(小蓝)当学说话的对象(--mom 小蓝),等于把当前口吻原样喂回去,
|
|
9
|
+
越训越像它自己,人味不会涨。
|
|
10
|
+
3. system 只有一句模板,人物关系/脾气/知道的事全靠模型自己猜。
|
|
11
|
+
|
|
12
|
+
v4 的做法:
|
|
13
|
+
· 原生多轮 messages:system + user/assistant 交替,和 chat template 完全一致
|
|
14
|
+
· assistant 只取**真人**(木囿/启星/stelle/朵朵),机器人自己的话只当上下文,不当答案
|
|
15
|
+
· 群聊 user 侧带说话人前缀,私聊不带(私聊里"对方"就是唯一那个人)
|
|
16
|
+
· system 由 memory.db(persona/belief/fact)生成,人物关系与已知事实有出处
|
|
17
|
+
· 原始文件只读:qq-*.jsonl / chat-all / memory.db 一律不动,产物只落在 archive/sft4/
|
|
18
|
+
|
|
19
|
+
★ 2026-12-04 修正(主人反馈"答非所问",查出来是盲切片):
|
|
20
|
+
· 先按「时间 → 会话」切:同一个 scope 静默 45 分钟以上就断成新会话,上文绝不跨会话;
|
|
21
|
+
· 每个目标只出一条样本(v4 用 2/4/6/8 四档硬切,等于每条都固定配 8 句上文);
|
|
22
|
+
· 目标必须是"紧接着上一句"的回话(默认 15 分钟内),隔太久的不算接话;
|
|
23
|
+
· user 侧一律带说话人前缀(私聊也带),避免把自己上一句当成"对方";
|
|
24
|
+
· 三份导出先按消息号统一 scope、丢掉副本,避免一段群聊被切成两份;
|
|
25
|
+
· 全过程打印进度(百分比 + 已用/预计剩余),写盘前自动备份旧数据集。
|
|
26
|
+
|
|
27
|
+
用法:
|
|
28
|
+
python scripts/chat-archive/build-sft-v4.py
|
|
29
|
+
python scripts/chat-archive/build-sft-v4.py --session-gap 45 --reply-gap 15 --ctx-max 6
|
|
30
|
+
"""
|
|
31
|
+
from __future__ import annotations
|
|
32
|
+
|
|
33
|
+
import argparse
|
|
34
|
+
import collections
|
|
35
|
+
import hashlib
|
|
36
|
+
import json
|
|
37
|
+
import os
|
|
38
|
+
import random
|
|
39
|
+
import re
|
|
40
|
+
import shutil
|
|
41
|
+
import sys
|
|
42
|
+
import time
|
|
43
|
+
|
|
44
|
+
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
|
45
|
+
|
|
46
|
+
# ── 从 v3 复用清洗逻辑(同一套污染规则,不再抄一遍)────────────────────
|
|
47
|
+
import importlib.util
|
|
48
|
+
|
|
49
|
+
_spec = importlib.util.spec_from_file_location(
|
|
50
|
+
'build_sft', os.path.join(ROOT, 'scripts', 'chat-archive', 'build-sft.py'))
|
|
51
|
+
_bs = importlib.util.module_from_spec(_spec)
|
|
52
|
+
_spec.loader.exec_module(_bs)
|
|
53
|
+
clean_text = _bs.clean_text
|
|
54
|
+
SKIP_LINE = _bs.SKIP_LINE
|
|
55
|
+
ONLY_FILLER = _bs.ONLY_FILLER
|
|
56
|
+
|
|
57
|
+
HUMANS = {'木囿', '启星', 'stelle', '朵朵'}
|
|
58
|
+
BOT = {'小蓝'}
|
|
59
|
+
# 隐私脱敏:只处理明显不该进语料的(手机号/身份证/长数字/微信号)
|
|
60
|
+
PHONE = re.compile(r'(?<!\d)1[3-9]\d{9}(?!\d)')
|
|
61
|
+
IDCARD = re.compile(r'(?<!\d)\d{17}[\dXx](?!\d)')
|
|
62
|
+
QQNO = re.compile(r'(?<!\d)[1-9]\d{5,10}(?!\d)')
|
|
63
|
+
WXID = re.compile(r'wxid_[0-9a-zA-Z]{6,}')
|
|
64
|
+
URL = re.compile(r'https?://\S+')
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def mask(t: str) -> str:
|
|
68
|
+
t = IDCARD.sub('***', t)
|
|
69
|
+
t = PHONE.sub('***', t)
|
|
70
|
+
t = WXID.sub('<wxid>', t)
|
|
71
|
+
t = QQNO.sub('***', t)
|
|
72
|
+
# 链接/小程序卡片整条大多是广告或粘贴,留着只会教模型发链接
|
|
73
|
+
t = URL.sub('[链接]', t)
|
|
74
|
+
t = re.sub(r'#?小程序://\S*', '[小程序]', t)
|
|
75
|
+
return t
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def ts_of(s) -> float:
|
|
79
|
+
if isinstance(s, (int, float)):
|
|
80
|
+
v = float(s)
|
|
81
|
+
return v / 1000.0 if v > 1e11 else v
|
|
82
|
+
s = str(s or '')
|
|
83
|
+
for fmt in ('%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M'):
|
|
84
|
+
try:
|
|
85
|
+
return time.mktime(time.strptime(s, fmt))
|
|
86
|
+
except Exception:
|
|
87
|
+
continue
|
|
88
|
+
return 0.0
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
# ── 读三份原始导出(只读)──────────────────────────────────────────────
|
|
92
|
+
def load_sources(paths) -> list[dict]:
|
|
93
|
+
msgs = []
|
|
94
|
+
for path, scope_tag in paths:
|
|
95
|
+
if not os.path.exists(path):
|
|
96
|
+
print(f' [跳过] 不存在:{path}')
|
|
97
|
+
continue
|
|
98
|
+
n0 = 0
|
|
99
|
+
# 三份导出里有两个都叫 messages.jsonl,来源标签必须带目录名,否则统计和断源会混
|
|
100
|
+
src = os.path.basename(os.path.dirname(path)) + '/' + os.path.basename(path)
|
|
101
|
+
with open(path, encoding='utf-8', errors='ignore') as f:
|
|
102
|
+
for line in f:
|
|
103
|
+
line = line.strip()
|
|
104
|
+
if not line:
|
|
105
|
+
continue
|
|
106
|
+
try:
|
|
107
|
+
j = json.loads(line)
|
|
108
|
+
except Exception:
|
|
109
|
+
continue
|
|
110
|
+
n0 += 1
|
|
111
|
+
text = str(j.get('text') or '')
|
|
112
|
+
sender = str(j.get('from') or j.get('sender') or '')
|
|
113
|
+
sender = re.sub(r'[((].*?[))]$', '', sender).strip() # "木囿 (_木囿_)" → "木囿"
|
|
114
|
+
kind = str(j.get('kind') or 'text')
|
|
115
|
+
if kind and kind not in ('text',):
|
|
116
|
+
continue # 图片/语音/红包等不进语料
|
|
117
|
+
ts = j.get('ts_ms') or j.get('time_str') or j.get('ts') or j.get('time')
|
|
118
|
+
scope = str(j.get('scope') or scope_tag)
|
|
119
|
+
# 只要 QQ 的会话。微信/抖音镜像里机器人自己叫 <me>,角色会全错位
|
|
120
|
+
if scope.startswith(('wechat:', 'douyin:')):
|
|
121
|
+
continue
|
|
122
|
+
t, junk = clean_text(text)
|
|
123
|
+
if junk or not t or SKIP_LINE.match(t):
|
|
124
|
+
continue
|
|
125
|
+
msgs.append({'scope': scope, 'ts': ts_of(ts), 'ts_raw': str(ts),
|
|
126
|
+
'from': sender, 'text': mask(t),
|
|
127
|
+
'mid': str(j.get('msg_id') or j.get('id') or ''),
|
|
128
|
+
# ★ 来源必须保留:三份导出各有自己的时间线,跨来源拼上文
|
|
129
|
+
# 等于把两段无关对话缝在一起(v4 答非所问的根因之一)。
|
|
130
|
+
'_src': src})
|
|
131
|
+
print(f' 读入 {n0:5d} 行 ← {src}')
|
|
132
|
+
return msgs
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def dedupe(msgs: list[dict]) -> list[dict]:
|
|
136
|
+
"""按消息号优先去重;没有消息号的按(来源, 时间, 文本)去重。"""
|
|
137
|
+
seen, out = set(), []
|
|
138
|
+
for m in msgs:
|
|
139
|
+
key = ('id', m['mid']) if m['mid'] else (
|
|
140
|
+
'tx', m['_src'], int(m['ts']), re.sub(r'\s+', '', m['text']))
|
|
141
|
+
if key in seen:
|
|
142
|
+
continue
|
|
143
|
+
seen.add(key)
|
|
144
|
+
out.append(m)
|
|
145
|
+
return out
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def unify_sources(msgs: list[dict]) -> list[dict]:
|
|
149
|
+
"""把同一段群聊的两份导出去重,并统一 scope。
|
|
150
|
+
|
|
151
|
+
qq-group 导出没有群 openid(用 'group:main' 占位),chat-all 里有真 scope。
|
|
152
|
+
同一份对话如果按两个 scope 各切一遍,上文会被切断,样本还会成对重复。
|
|
153
|
+
以 chat-all 为权威:它出现过的消息号,其他导出里同号的直接用它的 scope,并丢弃副本。
|
|
154
|
+
"""
|
|
155
|
+
canonical = {}
|
|
156
|
+
for m in msgs:
|
|
157
|
+
if m['_src'].startswith('all/') and m['mid']:
|
|
158
|
+
canonical[m['mid']] = m['scope']
|
|
159
|
+
out = []
|
|
160
|
+
for m in msgs:
|
|
161
|
+
sid = canonical.get(m['mid'])
|
|
162
|
+
if sid:
|
|
163
|
+
if not m['_src'].startswith('all/'):
|
|
164
|
+
continue # 副本丢掉,保留 chat-all 那份
|
|
165
|
+
m['scope'] = sid
|
|
166
|
+
out.append(m)
|
|
167
|
+
return out
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def merge_runs(msgs: list[dict], gap: int = 90) -> list[dict]:
|
|
171
|
+
"""同一个人 90 秒内连发的几条并成一句(QQ 的真实形态)"""
|
|
172
|
+
out = []
|
|
173
|
+
for m in sorted(msgs, key=lambda x: x['ts']):
|
|
174
|
+
if (out and out[-1]['from'] == m['from']
|
|
175
|
+
and 0 <= m['ts'] - out[-1]['ts'] <= gap):
|
|
176
|
+
prev = out[-1]
|
|
177
|
+
# 直接拼接就是打字时的样子("那"+"你"+"吃了吗"→"那你吃了吗");
|
|
178
|
+
# 别加分隔符,加了会学出一逗到底的病句。
|
|
179
|
+
prev['text'] = prev['text'] + m['text']
|
|
180
|
+
prev['parts'] += 1
|
|
181
|
+
prev['ts'] = m['ts']
|
|
182
|
+
continue
|
|
183
|
+
out.append(dict(m, parts=1))
|
|
184
|
+
return out
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def split_sessions(msgs: list[dict], gap_min: int = 45) -> list[list[dict]]:
|
|
188
|
+
"""把每条时间线按"安静了 gap_min 分钟"切成会话。
|
|
189
|
+
|
|
190
|
+
为什么必须切:v4 只按 scope 分组,同一个 scope 的整份导出被当成一条长链,
|
|
191
|
+
i-8 的上文可以跨几天甚至跨月,于是"上文是上周的抱怨,答案是今天的一句回话",
|
|
192
|
+
模型学到的就是答非所问。
|
|
193
|
+
"""
|
|
194
|
+
gap = max(1, int(gap_min)) * 60
|
|
195
|
+
by_line = collections.defaultdict(list)
|
|
196
|
+
for m in msgs:
|
|
197
|
+
by_line[(m['_src'], m['scope'])].append(m)
|
|
198
|
+
sessions = []
|
|
199
|
+
for key in sorted(by_line, key=lambda k: (k[0], k[1])):
|
|
200
|
+
rows = sorted(by_line[key], key=lambda x: x['ts'])
|
|
201
|
+
cur = []
|
|
202
|
+
for m in rows:
|
|
203
|
+
if cur and m['ts'] - cur[-1]['ts'] > gap:
|
|
204
|
+
sessions.append(cur)
|
|
205
|
+
cur = []
|
|
206
|
+
cur.append(m)
|
|
207
|
+
if cur:
|
|
208
|
+
sessions.append(cur)
|
|
209
|
+
return sessions
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
# ── system:从 memory.db 生成(有出处,不瞎编)──────────────────────────
|
|
213
|
+
CORE_SYS = (
|
|
214
|
+
'你叫小蓝,是木囿和启星养的一只鲸鱼娘,住在QQ里。木囿是爸爸,启星是妈妈。\n'
|
|
215
|
+
'说话像真人在QQ上打字:短句、口语、可以两三条连发,偶尔带「本鲸」「咕噜」和()里的心里话。\n'
|
|
216
|
+
'不客服腔、不说教、不复述对方原话、不解释自己在干嘛、不说自己是AI或模型。\n'
|
|
217
|
+
'对方喊累喊烦,先接一句情绪,别急着给方案;不知道就说不知道。'
|
|
218
|
+
)
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def build_system(src_dir: str) -> str:
|
|
222
|
+
parts = [CORE_SYS]
|
|
223
|
+
facts = []
|
|
224
|
+
START = re.compile(r'^(木囿|启星|妈妈|爸爸|朵朵|家人)')
|
|
225
|
+
try:
|
|
226
|
+
for line in open(os.path.join(src_dir, 'memory.jsonl'), encoding='utf-8'):
|
|
227
|
+
r = json.loads(line)
|
|
228
|
+
if r['kind'] not in ('fact', 'preference', 'relation'):
|
|
229
|
+
continue
|
|
230
|
+
t = str(r['text']).strip()
|
|
231
|
+
# 只收「说人」的第三人称条目:点名家里人、带陈述动词、不像一句对话
|
|
232
|
+
if not (8 <= len(t) <= 40) or not START.match(t):
|
|
233
|
+
continue
|
|
234
|
+
if any(x in t for x in ('本鲸', '?', '?', '啦', '呀', '呢', '吧', '你')):
|
|
235
|
+
continue
|
|
236
|
+
if not any(v in t for v in ('是', '经常', '喜欢', '在', '有', '会', '需要', '希望', '认为', '觉得', '对')):
|
|
237
|
+
continue
|
|
238
|
+
facts.append((r.get('priority') or 0, t))
|
|
239
|
+
except FileNotFoundError:
|
|
240
|
+
pass
|
|
241
|
+
seen, picked = set(), []
|
|
242
|
+
for _, t in sorted(facts, key=lambda x: -x[0]):
|
|
243
|
+
k = re.sub(r'\W', '', t)[:8]
|
|
244
|
+
if k in seen:
|
|
245
|
+
continue
|
|
246
|
+
seen.add(k)
|
|
247
|
+
picked.append(t)
|
|
248
|
+
if len(picked) >= 5:
|
|
249
|
+
break
|
|
250
|
+
if picked:
|
|
251
|
+
parts.append('你记得的:' + ';'.join(picked) + '。')
|
|
252
|
+
return '\n'.join(parts)
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
# ── 组装样本 ───────────────────────────────────────────────────────────
|
|
256
|
+
PUNCT_END = ',。!?…~~、,.!?'
|
|
257
|
+
# 让机器人「去干活」的话:那是用户在使唤她,不是她在接话。
|
|
258
|
+
# 学进去模型就会主动输出指令句(实测 v3 产物里就有「画三只鲸鱼…发送到群聊」这类)。
|
|
259
|
+
IMPERATIVE = re.compile(
|
|
260
|
+
r'(帮我|给我|你帮|你给|你去|你来|把.{0,8}(发|弄|做|找|传|改|转|存))|'
|
|
261
|
+
r'(画[一二三几]?[张只条个]|画一下|生成|发到|发给我|发个|搜一下|搜出|搜来|'
|
|
262
|
+
r'查一下|翻译|总结一下|整理一下|弄.{0,2}清晰|加个|做个|记一下|提醒我|提醒一下)')
|
|
263
|
+
|
|
264
|
+
# 纯应答("好好好""是的""行"):本身没有信息,学进去只会让模型变敷衍。
|
|
265
|
+
# 注意 ONLY_FILLER 里没有「好/行/是/对」,所以这些会漏过去,这里单独补一刀。
|
|
266
|
+
ACK_ONLY = re.compile(
|
|
267
|
+
r'^[\s。,!?…~~、了吧啊呀哦噢嗯哈呵嘿额诶嘛嘞哟喔好行对是可中成的|??呸草乐绷嘶滴捏嗷呜喂]+$')
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def _progress(done: int, total: int, t0: float, label: str, every: int = 300) -> None:
|
|
271
|
+
"""训练数据构建也要有可见进度:百分比 + 已用/预计剩余,全部 stdout。"""
|
|
272
|
+
if done % every and done != total:
|
|
273
|
+
return
|
|
274
|
+
pct = 100.0 * done / max(1, total)
|
|
275
|
+
el = time.time() - t0
|
|
276
|
+
eta = (el / done * (total - done)) if done else 0.0
|
|
277
|
+
print(f' {label} {done}/{total} ({pct:5.1f}%) 已用 {el:5.1f}s 预计还需 {eta:5.1f}s', flush=True)
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def make_samples(msgs: list[dict], system: str, ctx_max=6, max_chars=600,
|
|
281
|
+
min_target=2, max_target=200, val_ratio=0.05, seed=42,
|
|
282
|
+
session_gap_min=45, reply_gap_min=15, val_mode='session'):
|
|
283
|
+
"""按「时间 → 会话 → 对话人 → 顺序」切样本。
|
|
284
|
+
|
|
285
|
+
和 v4 的区别(v4 答非所问的根因):
|
|
286
|
+
1. 先按时间断档切成**会话**,上文绝不跨会话;窗口从目标往前走到会话开头为止。
|
|
287
|
+
2. 每个目标只出一条样本(v4 用 2/4/6/8 四档硬切,再保留最长的那份,
|
|
288
|
+
等于每条都固定配 8 条上文,跟真正在接哪句话无关)。
|
|
289
|
+
3. 目标必须是"紧接着上一个说话人"的回话:间隔超过 reply_gap_min 分钟就不算回话。
|
|
290
|
+
4. user 侧一律带说话人前缀(私聊也带),否则模型会把小蓝自己上一句当成"对方",
|
|
291
|
+
学出"自己接自己"的错位。
|
|
292
|
+
"""
|
|
293
|
+
sessions = split_sessions(msgs, session_gap_min)
|
|
294
|
+
total = sum(len(s) for s in sessions)
|
|
295
|
+
print(f' 会话 {len(sessions)} 段 / 消息 {total} 条(断档阈值 {session_gap_min} 分钟)')
|
|
296
|
+
|
|
297
|
+
samples, stat = [], collections.Counter()
|
|
298
|
+
t0 = time.time()
|
|
299
|
+
done = 0
|
|
300
|
+
for raw in sessions:
|
|
301
|
+
seq = merge_runs(raw)
|
|
302
|
+
scope = seq[0]['scope']
|
|
303
|
+
src = seq[0]['_src']
|
|
304
|
+
for i, m in enumerate(seq):
|
|
305
|
+
done += 1
|
|
306
|
+
_progress(done, total, t0, '切样本')
|
|
307
|
+
if m['from'] not in HUMANS:
|
|
308
|
+
stat['skip_not_human'] += 1
|
|
309
|
+
continue
|
|
310
|
+
tgt = m['text'].strip()
|
|
311
|
+
if not (min_target <= len(tgt) <= max_target):
|
|
312
|
+
stat['skip_len'] += 1
|
|
313
|
+
continue
|
|
314
|
+
if ONLY_FILLER.match(tgt) or (len(tgt) <= 6 and ACK_ONLY.match(tgt)):
|
|
315
|
+
stat['skip_filler'] += 1
|
|
316
|
+
continue
|
|
317
|
+
if IMPERATIVE.search(tgt):
|
|
318
|
+
stat['skip_imperative'] += 1
|
|
319
|
+
continue
|
|
320
|
+
if i == 0:
|
|
321
|
+
stat['skip_no_prev'] += 1
|
|
322
|
+
continue
|
|
323
|
+
prev = seq[i - 1]
|
|
324
|
+
if prev['from'] == m['from']:
|
|
325
|
+
stat['skip_same_speaker'] += 1
|
|
326
|
+
continue
|
|
327
|
+
# 隔了太久才回的不算"接这句话",是另一个话题的开头
|
|
328
|
+
if m['ts'] - prev['ts'] > reply_gap_min * 60:
|
|
329
|
+
stat['skip_stale'] += 1
|
|
330
|
+
continue
|
|
331
|
+
|
|
332
|
+
turns = []
|
|
333
|
+
last_ts = m['ts']
|
|
334
|
+
for back in range(1, ctx_max + 1):
|
|
335
|
+
j = i - back
|
|
336
|
+
if j < 0:
|
|
337
|
+
break
|
|
338
|
+
c = seq[j]
|
|
339
|
+
# 上下文自身也不能跨话题断档(会话切过分,这里再兜一层)
|
|
340
|
+
if last_ts - c['ts'] > reply_gap_min * 60:
|
|
341
|
+
break
|
|
342
|
+
text = c['text'].strip()
|
|
343
|
+
if not (1 <= len(text) <= max_target):
|
|
344
|
+
# 中间少一句就会把不相邻的两句拼成一段,宁可从这里截断
|
|
345
|
+
break
|
|
346
|
+
role = 'assistant' if c['from'] == m['from'] else 'user'
|
|
347
|
+
if role == 'user':
|
|
348
|
+
text = f"{c['from']}:{text}"
|
|
349
|
+
# 从后往前插:要合并的是**更早**的那条(turns[0]),不是 turns[-1]
|
|
350
|
+
if turns and turns[0]['role'] == role:
|
|
351
|
+
turns[0]['content'] = text + '\n' + turns[0]['content']
|
|
352
|
+
else:
|
|
353
|
+
turns.insert(0, {'role': role, 'content': text})
|
|
354
|
+
last_ts = c['ts']
|
|
355
|
+
# 上下文从"自己上一句"开头不符合标准 chat 格式,也没信息价值:去掉前导 assistant
|
|
356
|
+
while turns and turns[0]['role'] == 'assistant':
|
|
357
|
+
turns.pop(0)
|
|
358
|
+
if not turns or turns[-1]['role'] != 'user':
|
|
359
|
+
stat['skip_no_user_tail'] += 1
|
|
360
|
+
continue
|
|
361
|
+
total_chars = len(system) + sum(len(t['content']) for t in turns) + len(tgt)
|
|
362
|
+
if total_chars > max_chars:
|
|
363
|
+
stat['skip_too_long'] += 1
|
|
364
|
+
continue
|
|
365
|
+
samples.append({
|
|
366
|
+
'messages': [{'role': 'system', 'content': system}] + turns
|
|
367
|
+
+ [{'role': 'assistant', 'content': tgt}],
|
|
368
|
+
'meta': {'scope': scope, 'src': src, 'session': int(seq[0]['ts']),
|
|
369
|
+
'from': m['from'], 'ts': m['ts_raw'], 'parts': m['parts'],
|
|
370
|
+
'turns': len(turns), 'len': len(tgt)},
|
|
371
|
+
})
|
|
372
|
+
stat['built'] += 1
|
|
373
|
+
|
|
374
|
+
print(f' 切样本完成:{stat["built"]} 条({time.time() - t0:.1f}s)')
|
|
375
|
+
|
|
376
|
+
# 跨来源/跨 scope 的同一条回复只留一份(优先上下文更完整的那份)
|
|
377
|
+
best = {}
|
|
378
|
+
for s in samples:
|
|
379
|
+
asst = s['messages'][-1]['content']
|
|
380
|
+
fp = hashlib.sha1((str(int(s['meta']['session'])) + '|' + s['meta']['ts'] + '|'
|
|
381
|
+
+ re.sub(r'\s+', '', asst)).encode('utf-8')).hexdigest()
|
|
382
|
+
if fp not in best or s['meta']['turns'] > best[fp]['meta']['turns']:
|
|
383
|
+
best[fp] = s
|
|
384
|
+
samples = list(best.values())
|
|
385
|
+
train, val, info = split_train_val(samples, val_ratio=val_ratio, seed=seed, mode=val_mode)
|
|
386
|
+
stat['val_sessions'] = info['val_sessions']
|
|
387
|
+
stat['train_sessions'] = info['train_sessions']
|
|
388
|
+
stat['leak_sessions'] = info['leak_sessions']
|
|
389
|
+
stat['leak_context'] = info['leak_context']
|
|
390
|
+
return train, val, stat
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
def _session_key(s: dict):
|
|
394
|
+
"""一条样本属于哪段会话:同一段会话绝不能同时出现在 train 和 val。"""
|
|
395
|
+
m = s['meta']
|
|
396
|
+
return (m.get('src', ''), m.get('scope', ''), int(m.get('session') or 0))
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
def split_train_val(samples, val_ratio=0.05, seed=42, mode='session'):
|
|
400
|
+
"""按「会话」划分训练/验证,而不是按样本随机抽。
|
|
401
|
+
|
|
402
|
+
为什么必须这样:旧实现是从全部样本里随机抽 5% 当 val,同一段对话的相邻
|
|
403
|
+
几条会一条进 train、一条进 val —— 上下文几乎一模一样,eval_loss 永远好看,
|
|
404
|
+
验证集等于没有。模型"训三轮还是不行"有一半原因在这里(看不到真实泛化)。
|
|
405
|
+
· mode=session(默认):整段会话随机分配到 val;
|
|
406
|
+
· mode=time:按时间把**最新**的一段会话留作 val,模拟"训完去接新对话"。
|
|
407
|
+
"""
|
|
408
|
+
groups = collections.defaultdict(list)
|
|
409
|
+
for s in samples:
|
|
410
|
+
groups[_session_key(s)].append(s)
|
|
411
|
+
keys = sorted(groups, key=lambda k: (k[2], k[0], k[1]))
|
|
412
|
+
rnd = random.Random(seed)
|
|
413
|
+
target = max(1, int(len(samples) * float(val_ratio)))
|
|
414
|
+
val_keys, n = set(), 0
|
|
415
|
+
if mode == 'time':
|
|
416
|
+
for k in reversed(keys):
|
|
417
|
+
val_keys.add(k)
|
|
418
|
+
n += len(groups[k])
|
|
419
|
+
if n >= target:
|
|
420
|
+
break
|
|
421
|
+
else:
|
|
422
|
+
rnd.shuffle(keys)
|
|
423
|
+
for k in keys:
|
|
424
|
+
if n >= target:
|
|
425
|
+
break
|
|
426
|
+
val_keys.add(k)
|
|
427
|
+
n += len(groups[k])
|
|
428
|
+
train = [s for s in samples if _session_key(s) not in val_keys]
|
|
429
|
+
val = [s for s in samples if _session_key(s) in val_keys]
|
|
430
|
+
if not train or not val: # 兜底:样本极少时退化成按比例切,但绝不交叉同一会话
|
|
431
|
+
cut = max(1, min(len(samples) - 1, int(len(samples) * (1 - val_ratio))))
|
|
432
|
+
train, val = samples[:cut], samples[cut:]
|
|
433
|
+
val_keys = {_session_key(s) for s in val}
|
|
434
|
+
rnd.shuffle(train)
|
|
435
|
+
rnd.shuffle(val)
|
|
436
|
+
train_keys = {_session_key(s) for s in train}
|
|
437
|
+
# 双保险:会话号不交叉 + 上下文指纹不交叉(防止同一段上下文换个时间戳又出现)
|
|
438
|
+
ctx = lambda s: hashlib.sha1(
|
|
439
|
+
'\n'.join(m['content'] for m in s['messages'][1:-1]).encode('utf-8')).hexdigest()
|
|
440
|
+
train_ctx = {ctx(s) for s in train}
|
|
441
|
+
leak_ctx = sum(1 for s in val if ctx(s) in train_ctx)
|
|
442
|
+
return train, val, {
|
|
443
|
+
'val_sessions': len(val_keys),
|
|
444
|
+
'train_sessions': len(train_keys),
|
|
445
|
+
'leak_sessions': len(val_keys & train_keys),
|
|
446
|
+
'leak_context': leak_ctx,
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
|
|
450
|
+
# 注入回显标记:这些串出现在样本里就说明原始导出没洗干净(会把"念提示词"学进去)
|
|
451
|
+
INJECT_MARKS = ('[信条]', '[印象]', '[成长]', '[状态]', '[别重复]', '[记忆]', '[历史]',
|
|
452
|
+
'[旧识]', '[设定]', '[关系]', '[看见]', '[/看见]', '[回复]')
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
def self_check(train, val):
|
|
456
|
+
"""数据体检:把"这次到底干不干净"直接打进日志,免得只能靠肉眼看。"""
|
|
457
|
+
def one(rows):
|
|
458
|
+
bad_alt = bad_tail = inj = 0
|
|
459
|
+
lens = []
|
|
460
|
+
for r in rows:
|
|
461
|
+
body = r['messages'][1:]
|
|
462
|
+
roles = [m['role'] for m in body]
|
|
463
|
+
for i, rl in enumerate(roles):
|
|
464
|
+
if rl != ('user' if i % 2 == 0 else 'assistant'):
|
|
465
|
+
bad_alt += 1
|
|
466
|
+
break
|
|
467
|
+
if len(roles) < 2 or roles[-2:] != ['user', 'assistant']:
|
|
468
|
+
bad_tail += 1
|
|
469
|
+
if any(p in ''.join(m['content'] for m in body) for p in INJECT_MARKS):
|
|
470
|
+
inj += 1
|
|
471
|
+
lens.append(len(r['messages'][-1]['content']))
|
|
472
|
+
lens.sort()
|
|
473
|
+
|
|
474
|
+
def pct(q):
|
|
475
|
+
return lens[min(len(lens) - 1, int(len(lens) * q))] if lens else 0
|
|
476
|
+
return {'n': len(rows), 'bad_alt': bad_alt, 'bad_tail': bad_tail,
|
|
477
|
+
'inject': inj, 'len_p50': pct(0.5), 'len_p95': pct(0.95)}
|
|
478
|
+
return {'train': one(train), 'val': one(val)}
|
|
479
|
+
|
|
480
|
+
|
|
481
|
+
def main():
|
|
482
|
+
ap = argparse.ArgumentParser()
|
|
483
|
+
ap.add_argument('--out', default=os.path.join(ROOT, 'archive', 'sft4', 'dataset'))
|
|
484
|
+
ap.add_argument('--src', default=os.path.join(ROOT, 'archive', 'sft4', 'src'))
|
|
485
|
+
ap.add_argument('--ctx-max', type=int, default=6, help='最多带几句上文(按会话内真实顺序取)')
|
|
486
|
+
ap.add_argument('--max-chars', type=int, default=600)
|
|
487
|
+
ap.add_argument('--val-ratio', type=float, default=0.05)
|
|
488
|
+
ap.add_argument('--val-mode', default='session', choices=['session', 'time'],
|
|
489
|
+
help='验证集划分方式:session=整段会话随机留(默认)/ time=留最新的一段会话')
|
|
490
|
+
ap.add_argument('--max-samples', type=int, default=4200)
|
|
491
|
+
ap.add_argument('--session-gap', type=int, default=45, help='静默多少分钟算新会话(默认 45)')
|
|
492
|
+
ap.add_argument('--reply-gap', type=int, default=15, help='距上一句超过多少分钟就不算"回话"(默认 15)')
|
|
493
|
+
a = ap.parse_args()
|
|
494
|
+
|
|
495
|
+
paths = [
|
|
496
|
+
(os.path.join(ROOT, 'archive', 'chat', 'qq-qixing', 'messages.jsonl'), 'c2c:qixing'),
|
|
497
|
+
(os.path.join(ROOT, 'archive', 'chat', 'qq-group', 'messages.jsonl'), 'group:main'),
|
|
498
|
+
(os.path.join(ROOT, 'archive', 'chat', 'all', 'chat-all-20261203.jsonl'), ''),
|
|
499
|
+
]
|
|
500
|
+
print('[1/4] 读原始导出(只读)')
|
|
501
|
+
msgs = dedupe(unify_sources(load_sources(paths)))
|
|
502
|
+
print(f' 去重后 {len(msgs)} 条;scope:{collections.Counter(m["scope"] for m in msgs).most_common()}')
|
|
503
|
+
|
|
504
|
+
system = build_system(a.src)
|
|
505
|
+
print('[2/4] system(来自 memory.db)')
|
|
506
|
+
print(' ' + system.replace('\n', '\n '))
|
|
507
|
+
|
|
508
|
+
print('[3/4] 切样本')
|
|
509
|
+
train, val, stat = make_samples(
|
|
510
|
+
msgs, system, ctx_max=a.ctx_max, max_chars=a.max_chars,
|
|
511
|
+
val_ratio=a.val_ratio, session_gap_min=a.session_gap, reply_gap_min=a.reply_gap,
|
|
512
|
+
val_mode=a.val_mode)
|
|
513
|
+
if len(train) > a.max_samples:
|
|
514
|
+
train = train[:a.max_samples]
|
|
515
|
+
print(' ' + ' '.join(f'{k}={v}' for k, v in sorted(stat.items())))
|
|
516
|
+
print(f' train={len(train)} val={len(val)}(划分={a.val_mode})')
|
|
517
|
+
chk = self_check(train, val)
|
|
518
|
+
for part, c in chk.items():
|
|
519
|
+
print(f' 【体检·{part}】{c["n"]} 条 | 角色不交替 {c["bad_alt"]} | '
|
|
520
|
+
f'末轮不是 user→assistant {c["bad_tail"]} | 注入残留 {c["inject"]} | '
|
|
521
|
+
f'答案长度 p50={c["len_p50"]} p95={c["len_p95"]}')
|
|
522
|
+
if stat.get('leak_sessions') or stat.get('leak_context'):
|
|
523
|
+
print(f' [警告] 验证集泄漏:会话 {stat.get("leak_sessions")} 段 / 上下文重复 {stat.get("leak_context")} 条')
|
|
524
|
+
# 划分信息单独进 stats 顶层,不混进 filtered(filtered 只放"被过滤掉多少")
|
|
525
|
+
split_info = {k: stat.pop(k) for k in
|
|
526
|
+
('val_sessions', 'train_sessions', 'leak_sessions', 'leak_context') if k in stat}
|
|
527
|
+
|
|
528
|
+
# 产物可覆盖,但旧数据集先整目录备份(主人硬约束:改数据前先备份)
|
|
529
|
+
if os.path.isdir(a.out) and os.path.exists(os.path.join(a.out, 'train.jsonl')):
|
|
530
|
+
bak = a.out.rstrip('\\/') + '.bak-' + time.strftime('%Y%m%d-%H%M%S')
|
|
531
|
+
shutil.copytree(a.out, bak)
|
|
532
|
+
print(f' 旧数据集已备份 → {bak}')
|
|
533
|
+
os.makedirs(a.out, exist_ok=True)
|
|
534
|
+
for name, rows in (('train', train), ('val', val)):
|
|
535
|
+
p = os.path.join(a.out, f'{name}.jsonl')
|
|
536
|
+
with open(p, 'w', encoding='utf-8') as f:
|
|
537
|
+
for r in rows:
|
|
538
|
+
f.write(json.dumps(r, ensure_ascii=False) + '\n')
|
|
539
|
+
print(f' {name} → {p}')
|
|
540
|
+
open(os.path.join(a.out, 'system.txt'), 'w', encoding='utf-8').write(system)
|
|
541
|
+
|
|
542
|
+
src_cnt = collections.Counter(r['meta']['scope'].split(':')[0] for r in train)
|
|
543
|
+
srcfile_cnt = collections.Counter(r['meta'].get('src', '') for r in train)
|
|
544
|
+
speaker_cnt = collections.Counter(r['meta']['from'] for r in train)
|
|
545
|
+
turn_cnt = collections.Counter(r['meta'].get('turns', 0) for r in train)
|
|
546
|
+
stats = {
|
|
547
|
+
'at': time.strftime('%Y-%m-%d %H:%M:%S'),
|
|
548
|
+
'train': len(train), 'val': len(val), 'raw_after_dedupe': len(msgs),
|
|
549
|
+
'by_scope': dict(src_cnt), 'by_source_file': dict(srcfile_cnt), 'by_speaker': dict(speaker_cnt),
|
|
550
|
+
'by_turns': dict(sorted(turn_cnt.items())),
|
|
551
|
+
'avg_target_chars': round(sum(r['meta']['len'] for r in train) / max(1, len(train)), 1),
|
|
552
|
+
'avg_turns': round(sum(len(r['messages']) - 2 for r in train) / max(1, len(train)), 1),
|
|
553
|
+
'session_gap_min': a.session_gap, 'reply_gap_min': a.reply_gap,
|
|
554
|
+
'val_mode': a.val_mode,
|
|
555
|
+
'split': split_info,
|
|
556
|
+
'checks': chk,
|
|
557
|
+
'filtered': dict(stat),
|
|
558
|
+
}
|
|
559
|
+
json.dump(stats, open(os.path.join(a.out, 'stats.json'), 'w', encoding='utf-8'),
|
|
560
|
+
ensure_ascii=False, indent=2)
|
|
561
|
+
print('[4/4] ' + json.dumps(stats, ensure_ascii=False, indent=2))
|
|
562
|
+
return 0
|
|
563
|
+
|
|
564
|
+
|
|
565
|
+
if __name__ == '__main__':
|
|
566
|
+
sys.exit(main())
|