julianvolodia's picture
Super-squash branch 'main' using huggingface_hub
90264a9
Raw History Blame Contribute Delete
6.7 kB
"""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