Download clean.py from Masrkai/LinuxManuals: direct link, hf CLI and curl.
- Browser
- Download file 7.48 kB
-
https://huggingface.co/datasets/Masrkai/LinuxManuals/resolve/main/clean.py
- Command line
-
hf download hf://datasets/Masrkai/LinuxManuals/clean.py
-
curl -L -o clean.py https://huggingface.co/datasets/Masrkai/LinuxManuals/resolve/main/clean.py
7.48 kB
| #!/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) |