Download clean_wikipedia_jsonl.py from gmrrh/de-wiki: direct link, hf CLI and curl.
- Browser
- Download file 10 kB
-
https://huggingface.co/datasets/gmrrh/de-wiki/resolve/main/clean_wikipedia_jsonl.py
- Command line
-
hf download hf://datasets/gmrrh/de-wiki/clean_wikipedia_jsonl.py
-
curl -L -o clean_wikipedia_jsonl.py https://huggingface.co/datasets/gmrrh/de-wiki/resolve/main/clean_wikipedia_jsonl.py
10 kB
| """ | |
| clean_wikipedia_jsonl.py | |
| ======================== | |
| Post-process the JSONL output of fetch_wikipedia_de.py to fix common | |
| artifacts left behind by `mwparserfromhell.strip_code()` and apply a | |
| tighter length cap. | |
| Cleanup patterns applied (defaults — all individually disable-able) | |
| ------------------------------------------------------------------- | |
| 1. Image-cell residue: lines starting with image-related prefixes | |
| (`thumb|`, `mini|`, `rahmenlos|`, `zentriert|`, `links|`, `rechts|`, | |
| `gerahmt|`, `rahmen|`, `border|`, `framed|`, `upright|`, ...) | |
| followed by a pipe. Typical MediaWiki image-cell syntax. | |
| 2. Image-size-only cells: lines like `|300px|Description` that survive | |
| strip_code as standalone table cells. | |
| 3. External-reference footnote lines: German Wikipedia references of | |
| the form "Erklärvideo zu ... auf Youtube, abgerufen am 7. April | |
| 2024". Matched by the `abgerufen am` phrase with word boundaries. | |
| 4. Wiki category tags: `Kategorie:...` or `Category:...` lines. | |
| 5. File / image namespace links: `Datei:...`, `File:...`, `Bild:...`, | |
| `Image:...` lines. | |
| 6. Whitespace runs: 3+ consecutive newlines collapsed to 2. | |
| After cleanup: | |
| 7. Drop articles below --min-length or above --max-length chars. | |
| 8. Drop articles whose text became empty after cleanup. | |
| Streams line-by-line: safe for 10+ GB inputs, peak RAM is one article | |
| at a time. | |
| Usage | |
| ----- | |
| # Default cleanup (all patterns enabled, max-length 80k) | |
| python clean_wikipedia_jsonl.py in.jsonl out.jsonl | |
| # Soft cap (keep long articles) | |
| python clean_wikipedia_jsonl.py in.jsonl out.jsonl --max-length 500000 | |
| # Disable specific cleanups (e.g. for diff comparisons) | |
| python clean_wikipedia_jsonl.py in.jsonl out.jsonl --no-strip-image-cells | |
| python clean_wikipedia_jsonl.py in.jsonl out.jsonl --no-strip-external-refs | |
| python clean_wikipedia_jsonl.py in.jsonl out.jsonl --no-strip-categories | |
| python clean_wikipedia_jsonl.py in.jsonl out.jsonl --no-strip-file-links | |
| # Tighten both ends at once | |
| python clean_wikipedia_jsonl.py in.jsonl out.jsonl --min-length 2000 \ | |
| --max-length 50000 | |
| Stdlib only. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import re | |
| import sys | |
| import time | |
| from pathlib import Path | |
| # 1. Image-cell residue: lines starting with image-related prefixes | |
| # followed by a pipe and the cell content. | |
| IMAGE_CELL_PATTERN = re.compile( | |
| r"^[ \t]*(?:thumb|mini|rahmenlos|rahmen|zentriert|gerahmt|" | |
| r"border|framed|upright|links?|rechts?|vergrößern|verkleinern)" | |
| r"\|[^\n]*$", | |
| re.MULTILINE, | |
| ) | |
| # 2. Image-size-only cell: "|300px|Description" or "300px|Description" | |
| IMAGE_SIZE_PATTERN = re.compile( | |
| r"^[ \t]*\|?\d+px\|[^\n]*$", | |
| re.MULTILINE, | |
| ) | |
| # 3. External-reference footnote: "abgerufen am <date>" (German Wikipedia) | |
| EXTERNAL_REF_PATTERN = re.compile( | |
| r"^[ \t]*[^\n]*\babgerufen am\b[^\n]*$", | |
| re.MULTILINE, | |
| ) | |
| # 4. Wiki category tag: "Kategorie:..." or "Category:..." | |
| CATEGORY_PATTERN = re.compile( | |
| r"^[ \t]*(?:Kategorie|Category):[^\n]*$", | |
| re.MULTILINE, | |
| ) | |
| # 5. File / image namespace link residue: "Datei:...", "File:...", etc. | |
| FILE_LINK_PATTERN = re.compile( | |
| r"^[ \t]*(?:Datei|File|Bild|Image|Dateiarchiv):[^\n]*$", | |
| re.MULTILINE, | |
| ) | |
| # 6. Whitespace runs: 3+ newlines -> 2 | |
| WHITESPACE_RUN = re.compile(r"\n{3,}") | |
| def clean_text(text: str, *, strip_image_cells: bool, | |
| strip_external_refs: bool, strip_categories: bool, | |
| strip_file_links: bool) -> tuple[str, dict]: | |
| """Apply enabled cleanup patterns; return (cleaned_text, per-pattern_counts).""" | |
| counts = { | |
| "image_cells": 0, | |
| "image_sizes": 0, | |
| "external_refs": 0, | |
| "categories": 0, | |
| "file_links": 0, | |
| } | |
| if strip_image_cells: | |
| text, n = IMAGE_CELL_PATTERN.subn("", text) | |
| counts["image_cells"] = n | |
| text, n = IMAGE_SIZE_PATTERN.subn("", text) | |
| counts["image_sizes"] = n | |
| if strip_external_refs: | |
| text, n = EXTERNAL_REF_PATTERN.subn("", text) | |
| counts["external_refs"] = n | |
| if strip_categories: | |
| text, n = CATEGORY_PATTERN.subn("", text) | |
| counts["categories"] = n | |
| if strip_file_links: | |
| text, n = FILE_LINK_PATTERN.subn("", text) | |
| counts["file_links"] = n | |
| text = WHITESPACE_RUN.sub("\n\n", text) | |
| return text.strip(), counts | |
| def process(args: argparse.Namespace) -> None: | |
| src = Path(args.input) | |
| dst = Path(args.output) | |
| if not src.is_file(): | |
| print(f"[error] Input not found: {src}", file=sys.stderr) | |
| sys.exit(1) | |
| dst.parent.mkdir(parents=True, exist_ok=True) | |
| print(f"[info] {src} ({src.stat().st_size:,} bytes)", file=sys.stderr) | |
| print(f"[info] -> {dst}", file=sys.stderr) | |
| print( | |
| f"[info] min_length={args.min_length} max_length={args.max_length}", | |
| file=sys.stderr, | |
| ) | |
| print( | |
| f"[info] image_cells={not args.no_strip_image_cells} " | |
| f"external_refs={not args.no_strip_external_refs} " | |
| f"categories={not args.no_strip_categories} " | |
| f"file_links={not args.no_strip_file_links}", | |
| file=sys.stderr, | |
| ) | |
| stats = { | |
| "seen": 0, "kept": 0, | |
| "drop_invalid": 0, "drop_empty": 0, | |
| "drop_too_short": 0, "drop_too_long": 0, | |
| "lines_stripped": { | |
| "image_cells": 0, | |
| "image_sizes": 0, | |
| "external_refs": 0, | |
| "categories": 0, | |
| "file_links": 0, | |
| }, | |
| "chars_before": 0, | |
| "chars_after": 0, | |
| } | |
| started = time.time() | |
| with open(src, "rb") as fin, open(dst, "w", encoding="utf-8") as fout: | |
| for raw in fin: | |
| stats["seen"] += 1 | |
| try: | |
| ex = json.loads(raw) | |
| except json.JSONDecodeError: | |
| stats["drop_invalid"] += 1 | |
| continue | |
| if not isinstance(ex, dict) or "text" not in ex: | |
| stats["drop_invalid"] += 1 | |
| continue | |
| original = ex["text"] | |
| if not isinstance(original, str): | |
| stats["drop_invalid"] += 1 | |
| continue | |
| stats["chars_before"] += len(original) | |
| cleaned, counts = clean_text( | |
| original, | |
| strip_image_cells=not args.no_strip_image_cells, | |
| strip_external_refs=not args.no_strip_external_refs, | |
| strip_categories=not args.no_strip_categories, | |
| strip_file_links=not args.no_strip_file_links, | |
| ) | |
| for k, v in counts.items(): | |
| stats["lines_stripped"][k] += v | |
| if not cleaned: | |
| stats["drop_empty"] += 1 | |
| continue | |
| if len(cleaned) < args.min_length: | |
| stats["drop_too_short"] += 1 | |
| continue | |
| if len(cleaned) > args.max_length: | |
| stats["drop_too_long"] += 1 | |
| continue | |
| stats["chars_after"] += len(cleaned) | |
| fout.write(json.dumps({"text": cleaned}, ensure_ascii=False) + "\n") | |
| stats["kept"] += 1 | |
| if stats["seen"] % 500_000 == 0: | |
| elapsed = time.time() - started | |
| rate = stats["seen"] / elapsed if elapsed > 0 else 0.0 | |
| print( | |
| f"[progress] {stats['seen']:>10} seen | " | |
| f"{stats['kept']:>10} kept | " | |
| f"{rate:>7,.0f} lines/s", | |
| file=sys.stderr, | |
| ) | |
| elapsed = time.time() - started | |
| rate = stats["seen"] / elapsed if elapsed > 0 else 0.0 | |
| pct_kept = 100 * stats["kept"] / max(stats["seen"], 1) | |
| pct_chars = ( | |
| 100 * stats["chars_after"] / stats["chars_before"] | |
| if stats["chars_before"] else 0.0 | |
| ) | |
| print("\n[done] " + "=" * 56, file=sys.stderr) | |
| print(f" Articles seen : {stats['seen']:,}", file=sys.stderr) | |
| print(f" Articles kept : {stats['kept']:,} ({pct_kept:.2f}%)", | |
| file=sys.stderr) | |
| print(f" Chars in -> out : " | |
| f"{stats['chars_before']:,} -> {stats['chars_after']:,} " | |
| f"({pct_chars:.2f}%)", | |
| file=sys.stderr) | |
| print(f" Dropped (invalid): {stats['drop_invalid']:,}", file=sys.stderr) | |
| print(f" Dropped (empty) : {stats['drop_empty']:,}", file=sys.stderr) | |
| print(f" Dropped (short) : {stats['drop_too_short']:,}", file=sys.stderr) | |
| print(f" Dropped (long) : {stats['drop_too_long']:,}", file=sys.stderr) | |
| print(f" Lines stripped :", file=sys.stderr) | |
| for k, v in stats["lines_stripped"].items(): | |
| print(f" {k:<14}: {v:,}", file=sys.stderr) | |
| print(f" Elapsed : {elapsed:.1f}s ({rate:,.0f} lines/s)", | |
| file=sys.stderr) | |
| print("=" * 56, file=sys.stderr) | |
| def main() -> None: | |
| p = argparse.ArgumentParser( | |
| description=__doc__, | |
| formatter_class=argparse.RawDescriptionHelpFormatter, | |
| ) | |
| p.add_argument("input", help="Input JSONL file (e.g. wikipedia_de_clean.jsonl)") | |
| p.add_argument("output", help="Output JSONL file (overwritten)") | |
| p.add_argument("--max-length", type=int, default=80_000, | |
| help="Drop articles above N chars (default: 80000)") | |
| p.add_argument("--min-length", type=int, default=1_500, | |
| help="Drop articles below N chars (default: 1500)") | |
| p.add_argument("--no-strip-image-cells", action="store_true", | |
| help="Disable image-cell residue stripping (default: enabled)") | |
| p.add_argument("--no-strip-external-refs", action="store_true", | |
| help="Disable external-reference stripping (default: enabled)") | |
| p.add_argument("--no-strip-categories", action="store_true", | |
| help="Disable category-line stripping (default: enabled)") | |
| p.add_argument("--no-strip-file-links", action="store_true", | |
| help="Disable file/image-namespace link stripping (default: enabled)") | |
| args = p.parse_args() | |
| process(args) | |
| if __name__ == "__main__": | |
| main() |