File size: 6,702 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 167 168 169 170 171 172 173 174 175 176 177 178 179 | """Shared paths, Polish text normalisation, JSONL helpers and the curriculum parser.
All pipeline scripts run on the L40S server from /scratch/wiki_ext/scripts with /scratch/.venv/bin/python
(no extra packages: stdlib + openai/httpx/pyarrow that are already in the venv).
"""
import hashlib
import json
import os
import re
import unicodedata
from pathlib import Path
ROOT = Path(os.environ.get("WIKI_EXT_ROOT", "/scratch/wiki_ext"))
DB_PATH = Path(os.environ.get("WIKI_PL_DB", ROOT / "plwiki.sqlite"))
INPUT = ROOT / "input"
RUNS = ROOT / "runs"
PUBLISH = ROOT / "publish"
EPOCHS = ["starozytnosc", "sredniowiecze", "nowozytnosc", "xix_wiek", "1914_1945", "po_1945"]
EPOCH_NAMES = {
"starozytnosc": "starożytność",
"sredniowiecze": "średniowiecze",
"nowozytnosc": "nowożytność (XVI–XVIII w.)",
"xix_wiek": "XIX wiek (1795/1815–1914)",
"1914_1945": "lata 1914–1945",
"po_1945": "historia po 1945 r.",
}
# ---------------------------------------------------------------- normalisation
PL_MAP = str.maketrans("ąćęłńóśźżĄĆĘŁŃÓŚŹŻ", "acelnoszzACELNOSZZ")
def norm_pl(s):
"""Lowercase, ASCII-folded (ł->l too), alphanumeric tokens separated by single spaces."""
s = (s or "").translate(PL_MAP).lower()
s = unicodedata.normalize("NFKD", s)
s = "".join(ch for ch in s if not unicodedata.combining(ch))
return re.sub(r"[^a-z0-9]+", " ", s).strip()
STOP = set("""a aby ach ale albo ani az bardzo bez bo by byc byl byla byli bylo byly co czy czyli dla do dwa gdy
gdyz gdzie go i ich im in inne innych jak jaki jako je jego jej jest jesli jednak jego juz kiedy ktora ktore
ktorego ktorej ktory ktorych ktorym kto lub ma mial miala mu na nad nie niz nich o od oraz po pod podczas przez
przy r roku s sa sie ta tak takze tam te tego tej ten to tu tych tym u w we wiec wraz z za ze zas zostal
zostala zostalo zostaly jako np m in itp tj wiek wieku oraz jego ich""".split())
def stems(s, n=6, min_len=3):
"""Crude Polish 'stems': first n chars of informative tokens (numbers kept)."""
return [t[:n] for t in norm_pl(s).split() if (len(t) >= min_len or t.isdigit()) and t not in STOP]
def norm_leak(s):
"""Exactly the normalisation of scripts/build_sft_data.py (leakage shingles)."""
return re.sub(r"[^a-ząćęłńóśźż0-9]+", " ", (s or "").lower()).strip()
def shingles(s, n=80, step=40):
t = norm_leak(s)
return {t[i:i + n] for i in range(0, max(1, len(t) - n + 1), step)}
def stable_int(*parts):
return int(hashlib.sha256("|".join(map(str, parts)).encode()).hexdigest()[:12], 16)
# ---------------------------------------------------------------- JSONL
def read_jsonl(path):
path = Path(path)
if not path.exists():
return []
out = []
with open(path, encoding="utf-8") as f:
for line in f:
line = line.strip()
if line:
out.append(json.loads(line))
return out
def append_jsonl(path, rows):
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
with open(path, "a", encoding="utf-8") as f:
for r in rows:
f.write(json.dumps(r, ensure_ascii=False) + "\n")
def write_jsonl(path, rows):
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_suffix(path.suffix + ".tmp")
with open(tmp, "w", encoding="utf-8") as f:
for r in rows:
f.write(json.dumps(r, ensure_ascii=False) + "\n")
tmp.replace(path)
def done_ids(path, key="id"):
return {r.get(key) for r in read_jsonl(path)}
# ---------------------------------------------------------------- original tasks
def load_originals(epochs=None):
"""The 3600 verified tasks of data_synthetic/, in a stable order (epoch, file, line)."""
rows = []
for ep in epochs or EPOCHS:
for f in sorted((INPUT / "data_synthetic" / ep).glob("*.verified.jsonl")):
for i, r in enumerate(read_jsonl(f)):
r["_file"] = f"{ep}/{f.name}"
rows.append(r)
return rows
# ---------------------------------------------------------------- curriculum (podstawa programowa 2024)
CHAPTER_RE = re.compile(r"^\s*([IVXL]+)\s*\.\s+(\S.*)$")
ITEM_RE = re.compile(r"^\s*(\d{1,2})\)\s*(.*)$")
def parse_curriculum(epoch):
"""[{chapter, title, reqs: [{id: 'XXIX.2' | 'XXIX.R2', text}]}] from input/curriculum/podstawa_<epoch>.txt.
The PDF has two columns (basic / extended scope) that are sometimes interleaved in the text dump; an item
after 'a ponadto:' is an extended ('R') requirement unless its number continues the basic numbering.
"""
lines = (INPUT / "curriculum" / f"podstawa_{epoch}.txt").read_text(encoding="utf-8").splitlines()
chapters, cur, item, mode = [], None, None, "P"
last = {"P": 0, "R": 0}
def close_item():
nonlocal item
if item and cur is not None:
item["text"] = re.sub(r"\s+", " ", item["text"]).strip().rstrip(";.").strip()
cur["reqs"].append(item)
item = None
for raw in lines:
line = raw.strip()
if not line or re.fullmatch(r"\d{1,3}", line):
continue
m = CHAPTER_RE.match(line)
if m and not ITEM_RE.match(line):
close_item()
title = re.sub(r"\s*Uczeń:?\s*$", "", m.group(2)).strip().rstrip(".")
cur = {"chapter": m.group(1), "title": title, "reqs": []}
chapters.append(cur)
mode, last = "P", {"P": 0, "R": 0}
continue
if cur is None:
continue
if "a ponadto" in line:
close_item()
mode = "R"
continue
if line.startswith("spełnia wymagania"):
close_item()
continue
m = ITEM_RE.match(line)
if m:
n = int(m.group(1))
close_item()
kind = mode
if mode == "R" and n != last["R"] + 1 and n == last["P"] + 1:
kind = "P" # interleaved basic column
last[kind] = n
rid = f"{cur['chapter']}.{'R' if kind == 'R' else ''}{n}"
item = {"id": rid, "text": m.group(2)}
continue
if item is not None:
item["text"] += " " + line
elif cur["reqs"] == [] and not line.startswith("Uczeń"):
cur["title"] = (cur["title"] + " " + re.sub(r"\s*Uczeń:?\s*$", "", line)).strip()
close_item()
for c in chapters:
c["title"] = re.sub(r"\s+", " ", c["title"]).strip().rstrip(".")
for r in c["reqs"]:
r["text"] = re.sub(r"(\w)- (\w)", r"\1-\2", r["text"]) # 'polsko- krzyżackie' (line break)
return chapters
|