julianvolodia's picture
Super-squash branch 'main' using huggingface_hub
90264a9
Raw History Blame Contribute Delete
14.9 kB
#!/usr/bin/env python3
"""Polish Wikipedia lookup over plwiki.sqlite: title resolution, passage selection, excerpt verification.
python wiki.py resolve "Ksawery Drucki-Lubecki" "Sejm Wielki"
python wiki.py get "Unia lubelska" [--max_chars 3000]
python wiki.py search "unia polsko-litewska Krewo" [-k 10]
python wiki.py passages --titles "Unia lubelska|Zygmunt II August" --query "sejm lubelski 1569 unia realna"
python wiki.py check --title "Unia lubelska" --text "…"
"""
import argparse
import json
import re
import sqlite3
import sys
import zlib
from collections import OrderedDict
from common import DB_PATH, STOP, norm_pl, stems
SNAP_LABEL = {"fw2508": "FineWiki pl (zrzut HTML polskiej Wikipedii, VIII 2025)",
"w2311": "wikimedia/wikipedia 20231101.pl (zrzut XI 2023)"}
SKIP_SECTIONS = {"przypisy", "bibliografia", "linki zewnetrzne", "zobacz tez", "uwagi", "literatura", "galeria",
"filmografia", "dyskografia", "przypisy i bibliografia", "zrodla", "linki", "publikacje",
"wybrane publikacje", "wybrana bibliografia", "bibliografia i przypisy", "noty", "nota",
"literatura przedmiotu", "dalsza lektura", "materialy", "multimedia"}
NOTE_RE = re.compile(r"\[(?:\d{1,3}|[a-zA-Z]{1,2}|potrzebny przypis|uwaga \d+|przypis \d+)\]")
SENT_SPLIT = re.compile(r"(?<=[.!?…])\s+(?=[A-ZĄĆĘŁŃÓŚŹŻ0-9„\"(])")
ELLIPSIS = re.compile(r"\s*(?:\[\s*(?:\.\.\.|…)\s*\]|\(\s*(?:\.\.\.|…)\s*\))\s*")
def clean_text(s):
s = NOTE_RE.sub("", s)
s = s.replace("**", "").replace("__", "")
return re.sub(r"[ \t ]+", " ", s).strip()
def canon(s):
"""Normalisation for verbatim comparison: quotes, dashes, spaces, ellipsis, footnote marks, case."""
s = NOTE_RE.sub("", s or "")
s = s.replace(" ", " ").replace(" ", " ").replace(" ", " ").replace("­", "")
s = re.sub(r"[„”“\"«»]", '"', s)
s = re.sub(r"[‘’‚`']", "'", s)
s = re.sub(r"[–—−‑‒-]", "-", s)
s = s.replace("…", "...").replace("**", "")
return re.sub(r"\s+", " ", s).strip().lower()
def weight(stem):
return 2.0 if stem.isdigit() else 1.5 if len(stem) >= 6 else 1.0
class Wiki:
def __init__(self, path=DB_PATH):
self.db = sqlite3.connect(f"file:{path}?mode=ro", uri=True, check_same_thread=False)
self.db.execute("PRAGMA cache_size=-200000")
self.db.execute("PRAGMA mmap_size=12000000000")
self._pages = OrderedDict()
# ------------------------------------------------------------ pages
def page(self, pid):
if pid in self._pages:
self._pages.move_to_end(pid)
return self._pages[pid]
r = self.db.execute("SELECT pid, snap, page_id, title, url, wikidata_id, date_modified, lead, text_z "
"FROM page WHERE pid=?", (pid,)).fetchone()
if not r:
return None
p = dict(zip(["pid", "snap", "page_id", "title", "url", "wikidata_id", "date_modified", "lead"], r[:8]))
p["text"] = zlib.decompress(r[8]).decode("utf-8")
self._pages[pid] = p
if len(self._pages) > 3000:
self._pages.popitem(last=False)
return p
def ref(self, pid):
p = self.page(pid)
return {"title": p["title"], "url": p["url"], "snap": p["snap"], "date_modified": p["date_modified"]}
def _by_tn(self, tn):
return self.db.execute("SELECT pid, snap, title FROM page WHERE title_norm=? ORDER BY snap='w2311'",
(tn,)).fetchall()
# ------------------------------------------------------------ title resolution
def resolve(self, title, _depth=0):
"""(pid, how) for a Wikipedia title as proposed by an LLM; FineWiki preferred, 2023 dump as fallback."""
title = (title or "").strip().strip('"„”')
tn = norm_pl(title)
if not tn:
return None, None
hit = self._by_tn(tn)
if hit:
return hit[0][0], ("exact" if hit[0][2] == title else "norm") + ("" if hit[0][1] == "fw2508" else "@2311")
a = self.db.execute("SELECT target FROM alias WHERE src_norm=?", (tn,)).fetchone()
if a:
hit = self._by_tn(norm_pl(a[0]))
if hit:
return hit[0][0], "alias"
base = re.sub(r"\s*\([^)]*\)\s*$", "", title)
if base != title and _depth == 0:
pid, how = self.resolve(base, 1)
if pid:
return pid, "noparen:" + how
toks = [t for t in tn.split() if t not in STOP]
if not toks:
return None, None
q = " AND ".join(f'"{t[:7]}"*' for t in toks[:8])
try:
cands = self.db.execute("SELECT rowid FROM page_fts WHERE page_fts MATCH ? "
"ORDER BY bm25(page_fts, 10.0, 1.0) LIMIT 25",
(f"title_norm : ({q})",)).fetchall()
except sqlite3.OperationalError:
return None, None
want = set(stems(title, 7))
best, best_s = None, 0.0
for (pid,) in cands:
r = self.db.execute("SELECT title, snap FROM page WHERE pid=?", (pid,)).fetchone()
got = set(stems(r[0], 7))
if not got:
continue
s = len(want & got) / len(want | got) + (0.05 if r[1] == "fw2508" else 0) - 0.01 * len(r[0]) / 40
if s > best_s:
best, best_s = pid, s
if best and best_s >= 0.5:
return best, "fts"
return None, None
def other_snapshot(self, pid):
p = self.page(pid)
other = "w2311" if p["snap"] == "fw2508" else "fw2508"
r = self.db.execute("SELECT pid FROM page WHERE snap=? AND page_id=?", (other, p["page_id"])).fetchone()
if not r:
r = self.db.execute("SELECT pid FROM page WHERE title_norm=? AND +snap=?",
(norm_pl(p["title"]), other)).fetchone()
return r[0] if r else None
def lead_diff(self, pid):
"""1 - Jaccard of lead stems between the two snapshots (None if the article is in one snapshot only)."""
o = self.other_snapshot(pid)
if not o:
return None
a, b = set(stems(self.page(pid)["lead"][:700])), set(stems(self.page(o)["lead"][:700]))
return round(1 - len(a & b) / max(1, len(a | b)), 3)
# ------------------------------------------------------------ search
def search(self, query, k=10):
toks = list(dict.fromkeys(stems(query, 6)))[:8]
if not toks:
return []
rows = []
for op in (" AND ", " OR "):
q = op.join(f'"{t}"*' for t in toks)
try:
rows = self.db.execute("SELECT rowid FROM page_fts WHERE page_fts MATCH ? "
"ORDER BY bm25(page_fts, 8.0, 1.0) LIMIT ?", (q, k * 3)).fetchall()
except sqlite3.OperationalError:
rows = []
if len(rows) >= min(3, k):
break
out, seen = [], set()
for (pid,) in rows:
p = self.page(pid)
key = norm_pl(p["title"])
if key in seen:
continue
seen.add(key)
out.append({"pid": pid, "title": p["title"], "snap": p["snap"], "lead": p["lead"][:200]})
if len(out) >= k:
break
return out
# ------------------------------------------------------------ paragraphs
def blocks(self, pid):
"""[(section, kind, text)] with kind p (prose paragraph) | list | table; skips bibliography-like sections."""
p = self.page(pid)
lines = p["text"].split("\n")
fw = p["snap"] == "fw2508"
if lines and lines[0].startswith("# "):
lines = lines[1:]
out, buf, section = [], [], "wstęp"
def flush():
if not buf:
return
txt = "\n".join(buf).strip()
buf.clear()
if not txt or norm_pl(section) in SKIP_SECTIONS:
return
first = txt.lstrip()
kind = ("table" if first.startswith("|") else
"list" if re.match(r"^(?:[-*•] |\d+\. )", first) or (not fw and txt.startswith(" ")) else "p")
out.append((section, kind, clean_text(txt.replace("\n", " ")) if kind == "p" else txt))
for i, line in enumerate(lines):
m = re.match(r"^(#{2,6})\s+(.*)$", line) if fw else None
if m:
flush()
section = m.group(2).strip()
continue
if not fw and line.strip() and len(line.strip()) < 60 and not re.search(r"[.:;,]$", line.strip()) \
and (i + 1 < len(lines) and not lines[i + 1].strip()) and (i == 0 or not lines[i - 1].strip()):
flush()
section = line.strip()
continue
if not line.strip():
flush()
continue
buf.append(line)
flush()
return out
def article_text(self, pid):
"""Clean prose of the whole article (for verbatim checks)."""
return " ".join(t for _, k, t in self.blocks(pid) if k == "p")
# ------------------------------------------------------------ passages for prompts
@staticmethod
def window(text, qstems, max_chars):
if len(text) <= max_chars:
return text
sents = SENT_SPLIT.split(text)
best, best_s = "", -1.0
for i in range(len(sents)):
cur, j = "", i
while j < len(sents) and len(cur) + len(sents[j]) + 1 <= max_chars:
cur = (cur + " " + sents[j]).strip()
j += 1
if not cur:
continue
s = sum(weight(x) for x in set(stems(cur)) if x in qstems) - 0.1 * i
if s > best_s:
best, best_s = cur, s
return best or text[:max_chars].rsplit(" ", 1)[0]
def passages(self, pids, query, exclude="", max_total=4, per_article=2, max_chars=700, lead_first=True):
"""Best prose paragraphs of the given articles for a query (answer stems in `exclude` are not rewarded)."""
ex = set(stems(exclude))
q = {s for s in stems(query) if s not in ex}
cands = []
for rank, pid in enumerate(dict.fromkeys(p for p in pids if p)):
for i, (sec, kind, txt) in enumerate(self.blocks(pid)):
if kind != "p" or len(txt) < 80:
continue
s = sum(weight(x) for x in set(stems(txt)) if x in q)
cands.append({"score": s + (1.0 if i == 0 else 0) - 0.3 * rank, "rank": rank, "i": i, "pid": pid,
"section": sec, "text": txt})
chosen, per = [], {}
if lead_first:
lead = next((c for c in cands if c["rank"] == 0 and c["i"] == 0), None)
if lead:
chosen.append(lead)
per[lead["pid"]] = 1
for c in sorted(cands, key=lambda c: -c["score"]):
if len(chosen) >= max_total:
break
if c in chosen or per.get(c["pid"], 0) >= per_article or c["score"] <= 0.5:
continue
chosen.append(c)
per[c["pid"]] = per.get(c["pid"], 0) + 1
out = []
for c in chosen:
p = self.page(c["pid"])
out.append({"pid": c["pid"], "title": p["title"], "url": p["url"], "snap": p["snap"],
"date_modified": p["date_modified"], "section": c["section"],
"text": self.window(c["text"], q, max_chars)})
return out
# ------------------------------------------------------------ verbatim excerpt check
def check_excerpt(self, excerpt, pids):
"""Every segment between '[…]' must occur in order in one article (raw prose or with parentheses removed).
Returns (ok, message, pid)."""
segs = [s.strip(" .,;:-") for s in ELLIPSIS.split(canon(excerpt))]
segs = [s for s in segs if s]
if not segs:
return False, "pusty fragment", None
if len(segs) > 5:
return False, "za dużo opuszczeń […] (maks. 4)", None
short = [s for s in segs if len(s) < 15]
if short and len(segs) > 1:
return False, f"zbyt krótki segment między opuszczeniami: „{short[0]}”", None
worst = segs[0]
for pid in dict.fromkeys(p for p in pids if p):
raw = self.article_text(pid)
variants = [canon(raw), canon(re.sub(r"\s*\([^()]*\)", "", raw))]
ok_all, pos = True, {0: 0, 1: 0}
for s in segs:
found = False
for vi, v in enumerate(variants):
j = v.find(s, pos[vi])
if j >= 0:
pos[vi] = j + len(s)
found = True
break
if not found:
ok_all, worst = False, s
break
if ok_all:
return True, "ok", pid
return False, f"nie znaleziono dosłownie w artykule: „{worst[:120]}”", None
def main():
ap = argparse.ArgumentParser()
ap.add_argument("cmd", choices=["resolve", "get", "search", "passages", "check"])
ap.add_argument("args", nargs="*")
ap.add_argument("--max_chars", type=int, default=2500)
ap.add_argument("-k", type=int, default=10)
ap.add_argument("--titles", default="")
ap.add_argument("--query", default="")
ap.add_argument("--title", default="")
ap.add_argument("--text", default="")
a = ap.parse_args()
w = Wiki()
if a.cmd == "resolve":
for t in a.args:
pid, how = w.resolve(t)
print(json.dumps({"q": t, "title": w.page(pid)["title"] if pid else None, "how": how,
"lead_diff": w.lead_diff(pid) if pid else None}, ensure_ascii=False))
elif a.cmd == "get":
pid, how = w.resolve(" ".join(a.args))
if not pid:
sys.exit("not found")
p = w.page(pid)
print(f"# {p['title']} ({p['snap']}, {how}, {p['url']}, lead_diff={w.lead_diff(pid)})")
for sec, kind, txt in w.blocks(pid):
print(f"[{sec} | {kind}] {txt[:a.max_chars]}\n")
elif a.cmd == "search":
for r in w.search(" ".join(a.args), a.k):
print(json.dumps(r, ensure_ascii=False))
elif a.cmd == "passages":
pids = [w.resolve(t)[0] for t in a.titles.split("|") if t.strip()]
for p in w.passages(pids, a.query):
print(json.dumps(p, ensure_ascii=False))
elif a.cmd == "check":
pid, _ = w.resolve(a.title)
print(w.check_excerpt(a.text, [pid]))
if __name__ == "__main__":
main()