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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Streaming cleaner for man-page JSONL dataset.
|
| 4 |
+
Fixed: robust overstrike removal (bold/underline) that doesn't eat characters.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import json
|
| 8 |
+
import re
|
| 9 |
+
import sys
|
| 10 |
+
|
| 11 |
+
# ----------------------------------------------------------------------
|
| 12 |
+
# 1. Overstrike removal – SAFE version
|
| 13 |
+
# ----------------------------------------------------------------------
|
| 14 |
+
def debold(text: str) -> str:
|
| 15 |
+
"""
|
| 16 |
+
Remove man-page overstrike sequences only when they follow the classic patterns:
|
| 17 |
+
X\bX (bold) → X
|
| 18 |
+
_\bX (underline) → X
|
| 19 |
+
All other backspace sequences are left untouched (shouldn't exist anyway).
|
| 20 |
+
"""
|
| 21 |
+
# Pattern 1: (character) \x08 (same character) -> keep the character
|
| 22 |
+
# Pattern 2: _ \x08 (any character) -> keep the character
|
| 23 |
+
# The lookahead (?=.) ensures we don't match a trailing backspace with nothing after it.
|
| 24 |
+
text = re.sub(r'(.)\x08(?=\1)', r'\1', text)
|
| 25 |
+
text = re.sub(r'_\x08(.)', r'\1', text)
|
| 26 |
+
# As a final safety net, remove any remaining isolated backspaces
|
| 27 |
+
text = text.replace('\x08', '')
|
| 28 |
+
return text
|
| 29 |
+
|
| 30 |
+
# ----------------------------------------------------------------------
|
| 31 |
+
# 2. Other cleaning helpers (unchanged logic)
|
| 32 |
+
# ----------------------------------------------------------------------
|
| 33 |
+
def strip_header_footer(text: str) -> str:
|
| 34 |
+
lines = text.splitlines()
|
| 35 |
+
if lines and re.match(r'^[A-Za-z0-9._-]+\([^)]+\)\s+', lines[0]):
|
| 36 |
+
lines.pop(0)
|
| 37 |
+
while lines and lines[-1].strip() == '':
|
| 38 |
+
lines.pop()
|
| 39 |
+
while lines and (
|
| 40 |
+
re.match(r'^[A-Za-z0-9._-]+\([^)]+\)\s*$', lines[-1].strip()) or
|
| 41 |
+
re.match(r'^[A-Z]+\s+\d{4}\s*$', lines[-1].strip())
|
| 42 |
+
):
|
| 43 |
+
lines.pop()
|
| 44 |
+
return '\n'.join(lines)
|
| 45 |
+
|
| 46 |
+
def normalize_quotes_dashes(text: str) -> str:
|
| 47 |
+
text = text.replace('``', '“').replace("''", '”')
|
| 48 |
+
return text
|
| 49 |
+
|
| 50 |
+
def unwrap_paragraphs(text: str) -> str:
|
| 51 |
+
paragraphs = text.split('\n\n')
|
| 52 |
+
new_paras = []
|
| 53 |
+
for para in paragraphs:
|
| 54 |
+
if not para.strip():
|
| 55 |
+
continue
|
| 56 |
+
lines = para.split('\n')
|
| 57 |
+
if all((not line) or line.startswith((' ', '\t')) for line in lines):
|
| 58 |
+
new_paras.append('\n'.join(lines))
|
| 59 |
+
else:
|
| 60 |
+
merged = ' '.join(line.strip() for line in lines if line.strip())
|
| 61 |
+
new_paras.append(merged)
|
| 62 |
+
return '\n\n'.join(new_paras)
|
| 63 |
+
|
| 64 |
+
def clean_manual(raw_text: str) -> str:
|
| 65 |
+
text = debold(raw_text) # ← FIXED overstrike removal
|
| 66 |
+
text = strip_header_footer(text)
|
| 67 |
+
text = normalize_quotes_dashes(text)
|
| 68 |
+
text = re.sub(r'\n{3,}', '\n\n', text)
|
| 69 |
+
text = unwrap_paragraphs(text)
|
| 70 |
+
text = re.sub(r'^NAME\n\s+', 'NAME\n', text, flags=re.MULTILINE)
|
| 71 |
+
return text.strip()
|
| 72 |
+
|
| 73 |
+
# ----------------------------------------------------------------------
|
| 74 |
+
# 3. Streaming processor with progress
|
| 75 |
+
# ----------------------------------------------------------------------
|
| 76 |
+
def process_dataset_streaming(input_path: str, output_cleaned: str, output_training: str = None):
|
| 77 |
+
cleaned_count = 0
|
| 78 |
+
pair_count = 0
|
| 79 |
+
|
| 80 |
+
with open(input_path, 'r', encoding='utf-8') as fin, \
|
| 81 |
+
open(output_cleaned, 'w', encoding='utf-8') as fout_cleaned:
|
| 82 |
+
|
| 83 |
+
fout_train = None
|
| 84 |
+
if output_training:
|
| 85 |
+
fout_train = open(output_training, 'w', encoding='utf-8')
|
| 86 |
+
|
| 87 |
+
try:
|
| 88 |
+
for line_no, line in enumerate(fin, 1):
|
| 89 |
+
line = line.strip()
|
| 90 |
+
if not line:
|
| 91 |
+
continue
|
| 92 |
+
try:
|
| 93 |
+
obj = json.loads(line)
|
| 94 |
+
except json.JSONDecodeError as e:
|
| 95 |
+
print(f"Warning: skipping invalid JSON at line {line_no}: {e}", file=sys.stderr)
|
| 96 |
+
continue
|
| 97 |
+
|
| 98 |
+
topic = obj.get('topic', '')
|
| 99 |
+
section = obj.get('section', '')
|
| 100 |
+
raw = obj.get('manual', '')
|
| 101 |
+
if not raw:
|
| 102 |
+
continue
|
| 103 |
+
|
| 104 |
+
cleaned = clean_manual(raw)
|
| 105 |
+
record_id = f"{topic}({section})" if section else topic
|
| 106 |
+
|
| 107 |
+
fout_cleaned.write(
|
| 108 |
+
json.dumps({"id": record_id, "text": cleaned}, ensure_ascii=False) + '\n'
|
| 109 |
+
)
|
| 110 |
+
cleaned_count += 1
|
| 111 |
+
|
| 112 |
+
if fout_train:
|
| 113 |
+
pairs = generate_training_pairs(cleaned, topic, section)
|
| 114 |
+
for pair in pairs:
|
| 115 |
+
fout_train.write(json.dumps(pair, ensure_ascii=False) + '\n')
|
| 116 |
+
pair_count += 1
|
| 117 |
+
|
| 118 |
+
if line_no % 1000 == 0:
|
| 119 |
+
print(f"🧹 Processed {line_no} lines | cleaned: {cleaned_count}",
|
| 120 |
+
file=sys.stderr, flush=True)
|
| 121 |
+
|
| 122 |
+
finally:
|
| 123 |
+
if fout_train:
|
| 124 |
+
fout_train.close()
|
| 125 |
+
|
| 126 |
+
print(f"\n✅ Done! Total lines: {line_no}")
|
| 127 |
+
print(f" Cleaned manuals → {output_cleaned} ({cleaned_count} records)")
|
| 128 |
+
if output_training:
|
| 129 |
+
print(f" Training pairs → {output_training} ({pair_count} examples)")
|
| 130 |
+
|
| 131 |
+
# ----------------------------------------------------------------------
|
| 132 |
+
# 4. Training pair generation (unchanged)
|
| 133 |
+
# ----------------------------------------------------------------------
|
| 134 |
+
def generate_training_pairs(cleaned_text: str, topic: str, section: str) -> list:
|
| 135 |
+
# ... (same as before)
|
| 136 |
+
if not cleaned_text:
|
| 137 |
+
return []
|
| 138 |
+
sections = split_into_sections(cleaned_text)
|
| 139 |
+
if not sections:
|
| 140 |
+
return [make_pair(f"What is the {topic} command?", cleaned_text[:1500])]
|
| 141 |
+
|
| 142 |
+
pairs = []
|
| 143 |
+
desc = sections.get('DESCRIPTION') or sections.get('NAME')
|
| 144 |
+
if desc:
|
| 145 |
+
pairs.append(make_pair(f"What does the `{topic}` command do?", desc.strip()))
|
| 146 |
+
syn = sections.get('SYNOPSIS')
|
| 147 |
+
if syn:
|
| 148 |
+
pairs.append(make_pair(f"How do you use `{topic}`?", syn.strip()))
|
| 149 |
+
opts = sections.get('OPTIONS')
|
| 150 |
+
if opts:
|
| 151 |
+
pairs.append(make_pair(f"What are the options of `{topic}`?", opts.strip()))
|
| 152 |
+
ex = sections.get('EXAMPLES')
|
| 153 |
+
if ex:
|
| 154 |
+
pairs.append(make_pair(f"Show me examples of using `{topic}`.", ex.strip()))
|
| 155 |
+
return pairs
|
| 156 |
+
|
| 157 |
+
def make_pair(user_query: str, assistant_answer: str) -> dict:
|
| 158 |
+
return {
|
| 159 |
+
"messages": [
|
| 160 |
+
{"role": "system", "content": "You are a helpful Linux assistant that explains commands from their man pages."},
|
| 161 |
+
{"role": "user", "content": user_query},
|
| 162 |
+
{"role": "assistant", "content": assistant_answer}
|
| 163 |
+
]
|
| 164 |
+
}
|
| 165 |
+
|
| 166 |
+
def split_into_sections(text: str) -> dict:
|
| 167 |
+
sections = {}
|
| 168 |
+
current_heading = None
|
| 169 |
+
current_content = []
|
| 170 |
+
for line in text.split('\n'):
|
| 171 |
+
if re.match(r'^[A-Z][A-Z ]+$', line.strip()) and len(line.strip()) > 2:
|
| 172 |
+
if current_heading:
|
| 173 |
+
sections[current_heading] = '\n'.join(current_content).strip()
|
| 174 |
+
current_heading = line.strip()
|
| 175 |
+
current_content = []
|
| 176 |
+
else:
|
| 177 |
+
if current_heading:
|
| 178 |
+
current_content.append(line)
|
| 179 |
+
if current_heading:
|
| 180 |
+
sections[current_heading] = '\n'.join(current_content).strip()
|
| 181 |
+
return sections
|
| 182 |
+
|
| 183 |
+
# ----------------------------------------------------------------------
|
| 184 |
+
if __name__ == '__main__':
|
| 185 |
+
# You can change these paths
|
| 186 |
+
input_file = "manuals_copy.json"
|
| 187 |
+
cleaned_output = "cleaned_manuals.jsonl"
|
| 188 |
+
training_output = "training_data.jsonl"
|
| 189 |
+
|
| 190 |
+
# If you only want the cleaned corpus and no pairs, set training_output = None
|
| 191 |
+
training_output = None
|
| 192 |
+
|
| 193 |
+
process_dataset_streaming(input_file, cleaned_output, training_output)
|
sort.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Sort a JSONL file of cleaned man pages alphabetically by "id".
|
| 4 |
+
Usage:
|
| 5 |
+
python sort_cleaned.py [input.jsonl] [output.jsonl]
|
| 6 |
+
Defaults:
|
| 7 |
+
input = cleaned_manuals.jsonl
|
| 8 |
+
output = sorted_manuals.jsonl
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import json
|
| 12 |
+
import sys
|
| 13 |
+
|
| 14 |
+
def sort_cleaned(input_path: str, output_path: str):
|
| 15 |
+
"""Load records, sort by 'id', write sorted JSONL."""
|
| 16 |
+
print(f"Loading {input_path} ...", file=sys.stderr)
|
| 17 |
+
records = []
|
| 18 |
+
|
| 19 |
+
with open(input_path, 'r', encoding='utf-8') as fin:
|
| 20 |
+
for line_no, line in enumerate(fin, 1):
|
| 21 |
+
line = line.strip()
|
| 22 |
+
if not line:
|
| 23 |
+
continue
|
| 24 |
+
try:
|
| 25 |
+
rec = json.loads(line)
|
| 26 |
+
records.append(rec)
|
| 27 |
+
except json.JSONDecodeError as e:
|
| 28 |
+
print(f"Warning: bad JSON at line {line_no}: {e}", file=sys.stderr)
|
| 29 |
+
|
| 30 |
+
if line_no % 10000 == 0:
|
| 31 |
+
print(f" loaded {line_no} records...", file=sys.stderr)
|
| 32 |
+
|
| 33 |
+
print(f"Loaded {len(records)} records. Sorting...", file=sys.stderr)
|
| 34 |
+
|
| 35 |
+
# Alphabetical sort by the "id" field
|
| 36 |
+
records.sort(key=lambda x: x.get("id", ""))
|
| 37 |
+
|
| 38 |
+
print(f"Writing sorted records to {output_path} ...", file=sys.stderr)
|
| 39 |
+
with open(output_path, 'w', encoding='utf-8') as fout:
|
| 40 |
+
for rec in records:
|
| 41 |
+
fout.write(json.dumps(rec, ensure_ascii=False) + '\n')
|
| 42 |
+
|
| 43 |
+
print("Done.", file=sys.stderr)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
if __name__ == "__main__":
|
| 47 |
+
# command‑line arguments or defaults
|
| 48 |
+
input_file = sys.argv[1] if len(sys.argv) > 1 else "cleaned_manuals.jsonl"
|
| 49 |
+
output_file = sys.argv[2] if len(sys.argv) > 2 else "sorted_manuals.jsonl"
|
| 50 |
+
|
| 51 |
+
sort_cleaned(input_file, output_file)
|