File size: 4,038 Bytes
cfe406c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Fetch Polish Wikimedia sibling projects (Wikinews/Wikivoyage/Wikibooks/Wikiquote)
from the official dumps into SpeakLeash-style .jsonl.zst, so build_dynaword.py
consumes them unchanged. All are CC-BY-SA (same basis as Wikipedia/Wikisource).

Mainspace (ns=0) only; redirects and empty pages dropped. Wikitext -> plaintext
via mwparserfromhell.

Usage:
  python3 src/fetch_wikimedia.py --out ~/Local/Ventures/Slayer/data/speakleash \
      --wikis plwikinews plwikivoyage plwikibooks plwikiquote
"""
from __future__ import annotations
import argparse, bz2, json, subprocess, time
from pathlib import Path
from urllib.request import urlopen, Request
from xml.etree.ElementTree import iterparse
import mwparserfromhell

DUMP = "https://dumps.wikimedia.org/{w}/latest/{w}-latest-pages-articles.xml.bz2"
UA = {"User-Agent": "polish-dynaword/0.1 (+research; openly-licensed corpus)"}
MIN_CHARS = 200
# wiki -> (file stem used by build_dynaword, human URL)
SITE = {
    "plwikinews":   ("https://pl.wikinews.org/wiki/", "news"),
    "plwikivoyage": ("https://pl.wikivoyage.org/wiki/", "travel"),
    "plwikibooks":  ("https://pl.wikibooks.org/wiki/", "howto"),
    "plwikiquote":  ("https://pl.wikiquote.org/wiki/", "quotes"),
}


def _local(tag):  # strip {namespace}
    return tag.rsplit("}", 1)[-1]


def download(w, cache):
    dst = cache / f"{w}.xml.bz2"
    if dst.exists() and dst.stat().st_size > 0:
        print(f"  cached {dst.name}"); return dst
    url = DUMP.format(w=w)
    print(f"  downloading {url}", flush=True)
    with urlopen(Request(url, headers=UA), timeout=120) as r, dst.open("wb") as f:
        while chunk := r.read(1 << 20):
            f.write(chunk)
    return dst


def pages(bz2_path):
    """Yield (title, wikitext) for mainspace, non-redirect pages."""
    with bz2.open(bz2_path, "rb") as fh:
        title = ns = text = None; redirect = False
        for ev, el in iterparse(fh, events=("end",)):
            t = _local(el.tag)
            if t == "title": title = el.text
            elif t == "ns": ns = el.text
            elif t == "redirect": redirect = True
            elif t == "text": text = el.text
            elif t == "page":
                if ns == "0" and not redirect and text:
                    yield title, text
                title = ns = text = None; redirect = False
                el.clear()


def strip(wikitext):
    try:
        return mwparserfromhell.parse(wikitext).strip_code(normalize=True, collapse=True).strip()
    except Exception:
        return ""


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--out", default="~/Local/Ventures/Slayer/data/speakleash")
    ap.add_argument("--wikis", nargs="+", default=list(SITE))
    args = ap.parse_args()
    out_dir = Path(args.out).expanduser(); out_dir.mkdir(parents=True, exist_ok=True)
    cache = out_dir / "_wikimedia_dumps"; cache.mkdir(exist_ok=True)

    for w in args.wikis:
        base_url, domain = SITE[w]
        print(f"[{w}] ({domain})", flush=True)
        src = download(w, cache)
        jsonl = out_dir / f"{w}.jsonl"
        kept = 0; t0 = time.time()
        with jsonl.open("w", encoding="utf-8") as fo:
            for title, wt in pages(src):
                text = strip(wt)
                if len(text) < MIN_CHARS:
                    continue
                fo.write(json.dumps({
                    "text": text,
                    "meta": {"url": base_url + (title or "").replace(" ", "_"),
                             "title": title, "wiki": w, "domain": domain},
                }, ensure_ascii=False) + "\n")
                kept += 1
                if kept % 2000 == 0:
                    print(f"  {kept:,} kept | {kept/(time.time()-t0):.0f}/s", flush=True)
        subprocess.run(["zstd", "-19", "-f", "--rm", str(jsonl),
                        "-o", str(out_dir / f"{w}.jsonl.zst")], check=True)
        print(f"  {w}: {kept:,} docs in {round(time.time()-t0)}s -> {w}.jsonl.zst", flush=True)


if __name__ == "__main__":
    main()