polish-dynaword / src /fetch_wikimedia.py
kacperwikiel's picture
Squash: collapse LFS history to reclaim private storage
cfe406c
Raw
History Blame Contribute Delete
4.04 kB
#!/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()