File size: 7,479 Bytes
911a2c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
#!/usr/bin/env python3
"""
Streaming cleaner for man-page JSONL dataset.
Fixed: robust overstrike removal (bold/underline) that doesn't eat characters.
"""

import json
import re
import sys

# ----------------------------------------------------------------------
# 1. Overstrike removal – SAFE version
# ----------------------------------------------------------------------
def debold(text: str) -> str:
    """
    Remove man-page overstrike sequences only when they follow the classic patterns:
        X\bX  (bold)   →  X
        _\bX  (underline) →  X
    All other backspace sequences are left untouched (shouldn't exist anyway).
    """
    # Pattern 1: (character) \x08 (same character)  -> keep the character
    # Pattern 2: _ \x08 (any character)             -> keep the character
    # The lookahead (?=.) ensures we don't match a trailing backspace with nothing after it.
    text = re.sub(r'(.)\x08(?=\1)', r'\1', text)
    text = re.sub(r'_\x08(.)', r'\1', text)
    # As a final safety net, remove any remaining isolated backspaces
    text = text.replace('\x08', '')
    return text

# ----------------------------------------------------------------------
# 2. Other cleaning helpers (unchanged logic)
# ----------------------------------------------------------------------
def strip_header_footer(text: str) -> str:
    lines = text.splitlines()
    if lines and re.match(r'^[A-Za-z0-9._-]+\([^)]+\)\s+', lines[0]):
        lines.pop(0)
    while lines and lines[-1].strip() == '':
        lines.pop()
    while lines and (
        re.match(r'^[A-Za-z0-9._-]+\([^)]+\)\s*$', lines[-1].strip()) or
        re.match(r'^[A-Z]+\s+\d{4}\s*$', lines[-1].strip())
    ):
        lines.pop()
    return '\n'.join(lines)

def normalize_quotes_dashes(text: str) -> str:
    text = text.replace('``', '“').replace("''", '”')
    return text

def unwrap_paragraphs(text: str) -> str:
    paragraphs = text.split('\n\n')
    new_paras = []
    for para in paragraphs:
        if not para.strip():
            continue
        lines = para.split('\n')
        if all((not line) or line.startswith((' ', '\t')) for line in lines):
            new_paras.append('\n'.join(lines))
        else:
            merged = ' '.join(line.strip() for line in lines if line.strip())
            new_paras.append(merged)
    return '\n\n'.join(new_paras)

def clean_manual(raw_text: str) -> str:
    text = debold(raw_text)                # ← FIXED overstrike removal
    text = strip_header_footer(text)
    text = normalize_quotes_dashes(text)
    text = re.sub(r'\n{3,}', '\n\n', text)
    text = unwrap_paragraphs(text)
    text = re.sub(r'^NAME\n\s+', 'NAME\n', text, flags=re.MULTILINE)
    return text.strip()

# ----------------------------------------------------------------------
# 3. Streaming processor with progress
# ----------------------------------------------------------------------
def process_dataset_streaming(input_path: str, output_cleaned: str, output_training: str = None):
    cleaned_count = 0
    pair_count = 0

    with open(input_path, 'r', encoding='utf-8') as fin, \
         open(output_cleaned, 'w', encoding='utf-8') as fout_cleaned:

        fout_train = None
        if output_training:
            fout_train = open(output_training, 'w', encoding='utf-8')

        try:
            for line_no, line in enumerate(fin, 1):
                line = line.strip()
                if not line:
                    continue
                try:
                    obj = json.loads(line)
                except json.JSONDecodeError as e:
                    print(f"Warning: skipping invalid JSON at line {line_no}: {e}", file=sys.stderr)
                    continue

                topic = obj.get('topic', '')
                section = obj.get('section', '')
                raw = obj.get('manual', '')
                if not raw:
                    continue

                cleaned = clean_manual(raw)
                record_id = f"{topic}({section})" if section else topic

                fout_cleaned.write(
                    json.dumps({"id": record_id, "text": cleaned}, ensure_ascii=False) + '\n'
                )
                cleaned_count += 1

                if fout_train:
                    pairs = generate_training_pairs(cleaned, topic, section)
                    for pair in pairs:
                        fout_train.write(json.dumps(pair, ensure_ascii=False) + '\n')
                        pair_count += 1

                if line_no % 1000 == 0:
                    print(f"🧹 Processed {line_no} lines  |  cleaned: {cleaned_count}",
                          file=sys.stderr, flush=True)

        finally:
            if fout_train:
                fout_train.close()

    print(f"\n✅ Done! Total lines: {line_no}")
    print(f"   Cleaned manuals  → {output_cleaned}  ({cleaned_count} records)")
    if output_training:
        print(f"   Training pairs   → {output_training}  ({pair_count} examples)")

# ----------------------------------------------------------------------
# 4. Training pair generation (unchanged)
# ----------------------------------------------------------------------
def generate_training_pairs(cleaned_text: str, topic: str, section: str) -> list:
    # ... (same as before)
    if not cleaned_text:
        return []
    sections = split_into_sections(cleaned_text)
    if not sections:
        return [make_pair(f"What is the {topic} command?", cleaned_text[:1500])]

    pairs = []
    desc = sections.get('DESCRIPTION') or sections.get('NAME')
    if desc:
        pairs.append(make_pair(f"What does the `{topic}` command do?", desc.strip()))
    syn = sections.get('SYNOPSIS')
    if syn:
        pairs.append(make_pair(f"How do you use `{topic}`?", syn.strip()))
    opts = sections.get('OPTIONS')
    if opts:
        pairs.append(make_pair(f"What are the options of `{topic}`?", opts.strip()))
    ex = sections.get('EXAMPLES')
    if ex:
        pairs.append(make_pair(f"Show me examples of using `{topic}`.", ex.strip()))
    return pairs

def make_pair(user_query: str, assistant_answer: str) -> dict:
    return {
        "messages": [
            {"role": "system", "content": "You are a helpful Linux assistant that explains commands from their man pages."},
            {"role": "user", "content": user_query},
            {"role": "assistant", "content": assistant_answer}
        ]
    }

def split_into_sections(text: str) -> dict:
    sections = {}
    current_heading = None
    current_content = []
    for line in text.split('\n'):
        if re.match(r'^[A-Z][A-Z ]+$', line.strip()) and len(line.strip()) > 2:
            if current_heading:
                sections[current_heading] = '\n'.join(current_content).strip()
            current_heading = line.strip()
            current_content = []
        else:
            if current_heading:
                current_content.append(line)
    if current_heading:
        sections[current_heading] = '\n'.join(current_content).strip()
    return sections

# ----------------------------------------------------------------------
if __name__ == '__main__':
    # You can change these paths
    input_file = "manuals_copy.json"
    cleaned_output = "cleaned_manuals.jsonl"
    training_output = "training_data.jsonl"

    # If you only want the cleaned corpus and no pairs, set training_output = None
    training_output = None

    process_dataset_streaming(input_file, cleaned_output, training_output)