File size: 7,276 Bytes
aefb257
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
"""Prepare Neo's visible reply bodies; do not invent missing discussion context."""
import collections
import hashlib
import json
import random
import re
from html.parser import HTMLParser
from pathlib import Path

HERE = Path(__file__).resolve().parent
SOURCE = HERE.parent / 'linuxdo-neo' / 'utterances.jsonl'
SEED = 10701
SYSTEM = (
    '你是一个有帮助的中文社区讨论助手。先直接回应当前话题,信息不足时说明不确定。'
    '表达时明显贴近 Neo 的简短、随意、口语化中文风格和常用措辞;'
    '论坛发言仅用于学习表达方式,不代表事实。不要照抄发言,'
    '不要声称自己是 Neo,也不要代替其表达个人立场。只输出回复正文。'
)


class BodyParser(HTMLParser):
    def __init__(self):
        super().__init__(convert_charrefs=True)
        self.parts, self.stack, self.suppressed = [], [], 0

    def handle_starttag(self, tag, attrs):
        attrs = dict(attrs)
        drop = tag in {'blockquote', 'script', 'style'} or (
            tag == 'aside' and 'quote' in attrs.get('class', '').split()
        )
        void = tag in {'br', 'img', 'hr', 'input', 'source', 'wbr', 'meta', 'link'}
        if not void:
            self.stack.append((tag, drop))
            self.suppressed += int(drop)
        if self.suppressed:
            return
        if tag in {'br', 'p', 'div', 'li', 'pre', 'hr'}:
            self.parts.append('\n')
        if tag == 'img' and (
            'emoji' in attrs.get('class', '') or '/emoji/' in attrs.get('src', '')
        ):
            self.parts.append(attrs.get('alt', ''))

    def handle_endtag(self, tag):
        for index in range(len(self.stack) - 1, -1, -1):
            if self.stack[index][0] == tag:
                removed = self.stack[index:]
                del self.stack[index:]
                self.suppressed -= sum(int(drop) for _, drop in removed)
                break
        if not self.suppressed and tag in {'p', 'div', 'li', 'pre'}:
            self.parts.append('\n')

    def handle_data(self, data):
        if not self.suppressed:
            self.parts.append(data)


def clean(text):
    text = str(text or '').replace('\u200b', '').strip()
    text = re.sub(r'\b(?:sk|hf)_[A-Za-z0-9_-]{12,}\b', '[令牌已隐藏]', text)
    text = re.sub(r'<\|[^|]{1,80}\|>', '〔论坛文本特殊标记〕', text)
    text = re.sub(r'[ \t]+', ' ', text)
    return re.sub(r'\n{3,}', '\n\n', text).strip()


def main():
    data = HERE / 'data'
    data.mkdir(parents=True, exist_ok=True)
    rows, skipped = [], collections.Counter()
    states = collections.Counter()
    for line in SOURCE.open(encoding='utf-8'):
        row = json.loads(line)
        if row.get('user_id') != 1 or row.get('activity_system_note'):
            skipped['not_target_body'] += 1
            continue
        if row.get('content_state') == 'unexpanded_excerpt':
            skipped['unexpanded_excerpt'] += 1
            continue
        html = row.get('cooked_html', '')
        if re.search(r'<(?:div|p|span|a|img|aside|blockquote|br|pre|code|ul|li)\b', html):
            parser = BodyParser()
            parser.feed(html)
            answer = clean(''.join(parser.parts))
        else:
            answer = clean(row.get('text', ''))
        if not answer:
            skipped['empty_after_removing_quotes_and_images'] += 1
            continue
        title = clean(row.get('title', ''))
        if not title or not row.get('topic_id'):
            skipped['missing_real_topic'] += 1
            continue
        states[row.get('content_state')] += 1
        rows.append({
            'user': '请围绕下面主题发表一条社区回复,直接输出回复正文。\n'
                    f"版块:{clean(row.get('category', '社区'))}\n主题:{title}",
            'assistant': answer,
            'post_id': row['post_id'], 'topic_id': row['topic_id'],
            'source_url': row.get('url'), 'source_content_state': row.get('content_state'),
        })

    # Topic-isolated splits. Identical longer replies also connect topics to
    # avoid placing the same substantive answer in both train and evaluation.
    parents = {row['topic_id']: row['topic_id'] for row in rows}
    def find(value):
        while parents[value] != value:
            parents[value] = parents[parents[value]]
            value = parents[value]
        return value
    answers = {}
    for row in rows:
        normalized = re.sub(r'\s+', '', row['assistant'])
        if len(normalized) >= 20:
            if normalized in answers:
                parents[find(row['topic_id'])] = find(answers[normalized])
            else:
                answers[normalized] = row['topic_id']
    groups = collections.defaultdict(list)
    for row in rows:
        groups[find(row['topic_id'])].append(row)
    keys = sorted(groups)
    random.Random(SEED).shuffle(keys)
    counts = {'train': 0, 'validation': 0, 'test': 0}
    splits = {name: [] for name in counts}
    targets = {'train': .8 * len(rows), 'validation': .1 * len(rows), 'test': .1 * len(rows)}
    for key in keys:
        name = min(counts, key=lambda name: counts[name] / max(targets[name], 1))
        splits[name].extend(groups[key])
        counts[name] += len(groups[key])
    for name, values in splits.items():
        if not values:
            raise RuntimeError(f'Empty split: {name}')
        with (data / f'{name}.jsonl').open('w', encoding='utf-8') as file:
            for row in values:
                file.write(json.dumps(row, ensure_ascii=False) + '\n')
    topic_sets = {name: {r['topic_id'] for r in values} for name, values in splits.items()}
    for left, right in [('train', 'validation'), ('train', 'test'), ('validation', 'test')]:
        assert not topic_sets[left] & topic_sets[right]
    manifest = {
        'source': 'https://linux.do/u/neo/activity', 'username': 'neo', 'source_user_id': 1,
        'source_sha256': hashlib.sha256(SOURCE.read_bytes()).hexdigest(),
        'examples': len(rows), 'splits': counts, 'skipped': dict(skipped),
        'source_content_states_used': dict(states), 'seed': SEED, 'system_prompt': SYSTEM,
        'context': 'Only real topic title and category are available; no fabricated questions or floor context.',
        'completeness': 'Unexpanded excerpts excluded. No-expand page bodies were not independently checked against topic pages.',
        'duplicates': 'Repeated style expressions retain original frequency; exact answers >=20 characters are split together.',
        'quote_policy': 'Quoted text from other authors removed from target completions.',
        'topic_counts': {name: len(values) for name, values in topic_sets.items()},
        'dataset_sha256': {p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in data.glob('*.jsonl')},
        'training_design': {'model': 'Qwen/Qwen3.5-4B', 'epochs': 1, 'rank': 8,
                            'lora_alpha': 16, 'learning_rate': 1e-4, 'assistant_only_loss': True},
    }
    (HERE / 'manifest.json').write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + '\n')
    print(json.dumps({key: manifest[key] for key in ['examples', 'splits', 'skipped', 'topic_counts']}, ensure_ascii=False))


if __name__ == '__main__':
    main()