File size: 7,681 Bytes
90264a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
#!/usr/bin/env python3
"""Build plwiki.sqlite from two Polish Wikipedia snapshots + the plwiki redirect dump (no API cost).

    python build_db.py pages     # corpus/finewiki (FineWiki pl, HTML dumps Aug 2025) + corpus/wikipedia (20231101.pl)
    python build_db.py aliases   # corpus/dumps/plwiki-latest-{page,redirect}.sql.gz -> alias table
    python build_db.py stats

Tables
    page(pid, snap, page_id, title, title_norm, url, wikidata_id, date_modified, lead, text_z, infobox_z)
        snap = 'fw2508' (FineWiki, primary) | 'w2311' (wikimedia/wikipedia 20231101.pl, fallback + cross-check)
        text_z = zlib(full article text); FineWiki text is markdown ('# Title', '## Section', tables, lists)
    page_fts(title_norm, lead_norm)  contentless FTS5, rowid = pid; w2311 pages only when the title is not in FineWiki
    alias(src_norm, src_title, target)  redirect title (normalised) -> target article title
    meta(k, v)
"""
import glob
import gzip
import json
import re
import sqlite3
import sys
import time
import zlib

import pyarrow.parquet as pq

from common import DB_PATH, ROOT, norm_pl

CORPUS = ROOT / "corpus"
SCHEMA = """
CREATE TABLE IF NOT EXISTS page(pid INTEGER PRIMARY KEY, snap TEXT, page_id INTEGER, title TEXT, title_norm TEXT,
  url TEXT, wikidata_id TEXT, date_modified TEXT, lead TEXT, text_z BLOB, infobox_z BLOB);
CREATE VIRTUAL TABLE IF NOT EXISTS page_fts USING fts5(title_norm, lead_norm, content='', tokenize='unicode61');
CREATE TABLE IF NOT EXISTS alias(src_norm TEXT PRIMARY KEY, src_title TEXT, target TEXT);
CREATE TABLE IF NOT EXISTS meta(k TEXT PRIMARY KEY, v TEXT);
"""


def connect():
    db = sqlite3.connect(DB_PATH)
    db.executescript("PRAGMA journal_mode=OFF; PRAGMA synchronous=OFF; PRAGMA cache_size=-400000;")
    db.executescript(SCHEMA)
    return db


def lead_of(text, fw):
    """Lead = paragraphs before the first section heading (FineWiki) or the first ~2 paragraphs (plain text)."""
    if fw:
        parts = text.split("\n", 1)
        body = (parts[1] if len(parts) > 1 else "") if text.startswith("# ") else text
        lead = re.split(r"\n#{2,6} ", body, maxsplit=1)[0]
    else:
        paras = [p for p in text.split("\n\n") if p.strip()]
        lead, n = "", 0
        for p in paras:
            lead += p + "\n\n"
            n += 1
            if len(lead) > 600 or n >= 2:
                break
    lead = "\n".join(l for l in lead.splitlines() if not l.lstrip().startswith("|"))
    return re.sub(r"\n{3,}", "\n\n", lead).strip()[:2500]


def build_pages():
    db = connect()
    db.execute("DELETE FROM page")
    db.execute("DELETE FROM page_fts")
    t0, n, fw_titles = time.time(), 0, set()
    sources = [("fw2508", sorted(glob.glob(str(CORPUS / "finewiki/data/plwiki/*.parquet"))),
                ["page_id", "title", "url", "wikidata_id", "date_modified", "text", "infoboxes"]),
               ("w2311", sorted(glob.glob(str(CORPUS / "wikipedia/20231101.pl/*.parquet"))),
                ["id", "title", "url", "text"])]
    for snap, files, cols in sources:
        for f in files:
            pf = pq.ParquetFile(f)
            for batch in pf.iter_batches(batch_size=2000, columns=cols):
                rows, fts = [], []
                for r in batch.to_pylist():
                    text, title = r["text"] or "", r["title"] or ""
                    if not text or not title:
                        continue
                    tn = norm_pl(title)
                    fw = snap == "fw2508"
                    lead = lead_of(text, fw)
                    ib = r.get("infoboxes")
                    n += 1
                    rows.append((n, snap, int(r.get("page_id") or r.get("id") or 0), title, tn, r["url"],
                                 r.get("wikidata_id"), r.get("date_modified"), lead,
                                 zlib.compress(text.encode("utf-8"), 6),
                                 zlib.compress(ib.encode("utf-8"), 6) if ib and ib != "[]" else None))
                    if fw:
                        fw_titles.add(tn)
                        fts.append((n, tn, norm_pl(lead[:900])))
                    elif tn not in fw_titles:
                        fts.append((n, tn, norm_pl(lead[:900])))
                db.executemany("INSERT INTO page VALUES (?,?,?,?,?,?,?,?,?,?,?)", rows)
                db.executemany("INSERT INTO page_fts(rowid, title_norm, lead_norm) VALUES (?,?,?)", fts)
                if n % 100000 < 2000:
                    db.commit()
                    print(f"[{time.time() - t0:6.0f}s] {snap} {n} pages", flush=True)
        db.commit()
    print("indexes...", flush=True)
    db.execute("CREATE INDEX IF NOT EXISTS page_tn ON page(title_norm)")
    db.execute("CREATE INDEX IF NOT EXISTS page_snap_pid ON page(snap, page_id)")
    db.execute("INSERT INTO page_fts(page_fts) VALUES('optimize')")
    counts = dict(db.execute("SELECT snap, count(*) FROM page GROUP BY snap").fetchall())
    meta = {"built_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "pages": json.dumps(counts),
            "fw2508": "HuggingFaceFW/finewiki config pl (data/plwiki, Wikipedia HTML dumps Aug 2025)",
            "w2311": "wikimedia/wikipedia config 20231101.pl"}
    db.executemany("INSERT OR REPLACE INTO meta VALUES (?,?)", meta.items())
    db.commit()
    print(f"done in {time.time() - t0:.0f}s: {counts}", flush=True)


STR = r"'((?:[^'\\]|\\.)*)'"


def unesc(s):
    return re.sub(r"\\(.)", r"\1", s).replace("_", " ")


def build_aliases():
    db = connect()
    page_gz = CORPUS / "dumps/plwiki-latest-page.sql.gz"
    red_gz = CORPUS / "dumps/plwiki-latest-redirect.sql.gz"
    header = gzip.open(page_gz, "rt", encoding="utf-8", errors="replace").read(6000)
    cols = re.findall(r"^\s+`(\w+)`", header.split("CREATE TABLE `page`", 1)[1].split(") ENGINE", 1)[0], re.M)
    assert cols[:4] == ["page_id", "page_namespace", "page_title", "page_is_redirect"], cols[:6]
    tup = re.compile(r"\((\d+),(-?\d+)," + STR + r",([01]),")
    redirect_title = {}
    t0 = time.time()
    with gzip.open(page_gz, "rt", encoding="utf-8", errors="replace") as f:
        for line in f:
            if line.startswith("INSERT INTO"):
                for m in tup.finditer(line):
                    if m.group(2) == "0" and m.group(4) == "1":
                        redirect_title[int(m.group(1))] = unesc(m.group(3))
    print(f"redirect pages (ns0): {len(redirect_title)} [{time.time() - t0:.0f}s]", flush=True)
    rtup = re.compile(r"\((\d+),(-?\d+)," + STR + r",")
    rows = []
    with gzip.open(red_gz, "rt", encoding="utf-8", errors="replace") as f:
        for line in f:
            if line.startswith("INSERT INTO"):
                for m in rtup.finditer(line):
                    src = redirect_title.get(int(m.group(1)))
                    if src and m.group(2) == "0":
                        rows.append((norm_pl(src), src, unesc(m.group(3))))
    db.execute("DELETE FROM alias")
    db.executemany("INSERT OR IGNORE INTO alias VALUES (?,?,?)", rows)
    db.execute("INSERT OR REPLACE INTO meta VALUES ('aliases', ?)",
               (f"plwiki-latest redirect+page dumps, {len(rows)} redirects, built "
                f"{time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())}",))
    db.commit()
    print(f"aliases: {len(rows)} [{time.time() - t0:.0f}s]", flush=True)


def stats():
    db = sqlite3.connect(f"file:{DB_PATH}?mode=ro", uri=True)
    for k, v in db.execute("SELECT k, v FROM meta"):
        print(f"{k}: {v}")
    print("alias rows:", db.execute("SELECT count(*) FROM alias").fetchone()[0])


if __name__ == "__main__":
    {"pages": build_pages, "aliases": build_aliases, "stats": stats}[sys.argv[1]]()