File size: 8,984 Bytes
da34da8 e731132 2dd8f71 da34da8 2dd8f71 da34da8 2dd8f71 da34da8 e731132 da34da8 | 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 | # -*- coding: utf-8 -*-
"""Reproduktivni pipeline za bh-reasoning-pilot-v01. CPU-only, stdlib + pandas/pyarrow.
Koraci: normalize -> validate -> math-consistency -> dedup -> classify -> split -> write -> report.
EVAL DISCIPLINA: test split je zakljucan held-out (10/10/80) i ne koristi se za trening."""
import hashlib, json, re, unicodedata
from pathlib import Path
import pandas as pd
from authored import TASKS as TASKS_V01
from authored_v02 import TASKS_V02
from authored_v03 import TASKS_V03
TASKS = list(TASKS_V01) + list(TASKS_V02) + list(TASKS_V03)
BASE = Path(__file__).resolve().parent.parent
DATA = BASE / "data"
REP = BASE / "reports"
VERSION = "v03"
LICENSE = "CC-BY-4.0"
SOURCE = "original-human-v01"
CREATED = "2026-12-01"
IJE_MARK = ["dje", "mlijeko", "vrijeme", "lijep", "bijel", "cijena", "svijet", "dijete",
"mjesec", "gdje", "ovdje", "rješenje", "slijedi", "vrijednost", "primjer"]
EKA_MARK = ["devojka", "mleko", "vreme", "lep", "belo", "cena", "svet", "dete", "mesec", "pesma"]
PII = [re.compile(p) for p in [r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}", r"\+?387\s?\d{2}\s?\d{3}\s?\d{3,4}", r"\b\d{13}\b"]]
HTML = re.compile(r"<[^>]+>")
REPCHAR = re.compile(r"(.)\1{5,}")
DIJAK = re.compile(r"[čćžšđČĆŽŠĐ]")
ALLOWED_LICENSES = {"CC-BY-4.0", "CC-BY-SA-4.0", "CC0-1.0", "Apache-2.0", "MIT", "ODC-BY"}
ALLOWED_SUBJECTS = {"math", "logic", "decision"}
def norm(s): return unicodedata.normalize("NFC", s.strip())
def hkey(s): return hashlib.sha256(norm(s).lower().encode()).hexdigest()
def grams(s):
s = re.sub(r"\s+", " ", norm(s).lower())
return {s[i:i+3] for i in range(max(0, len(s)-2))} or {""}
def jacc(a, b):
if not a or not b: return 0.0
return len(a & b) / len(a | b)
rows = []
for i, (subj, prob, steps, ans, sol) in enumerate(TASKS, 1):
assert isinstance(steps, list) and len(steps) >= 2, f"steps too short at {i}"
rows.append({"id": f"BH-REA-{i:04d}", "problem": norm(prob), "solution": norm(sol),
"answer": norm(ans), "steps": [norm(s) for s in steps],
"subject": subj, "eval_metric": "exact_match", "lang": "bs",
"variant": None, "script": "Latn", "source": SOURCE, "license": LICENSE, "created": CREATED})
df = pd.DataFrame(rows)
# validacija strukture
assert df["id"].is_unique, "duplicate ids"
assert (df[["problem", "solution", "answer"]] != "").all().all(), "empty required field"
assert set(df["subject"]) <= ALLOWED_SUBJECTS, "bad subject"
assert set(df["license"]) <= ALLOWED_LICENSES, "unknown license"
assert (df["steps"].map(len) >= 2).all(), "steps too short"
assert (df["subject"].value_counts() == pd.Series({"math": 280, "logic": 245, "decision": 175})).all(), \
f"bad subject distribution: {df['subject'].value_counts().to_dict()}"
# MATEMATICKA KONZISTENTNOST (nezavisna provjera): answer mora biti sadrzan u solution (NFC/lower),
# a kod math zadataka broj iz answera mora se pojaviti i u steps (koraci zaista izvode rezultat)
def acore(a): return re.sub(r"\s+", " ", unicodedata.normalize("NFC", a).lower()).strip().rstrip(".")
bad_sol = [r["id"] for _, r in df.iterrows() if acore(r["answer"]) not in unicodedata.normalize("NFC", r["solution"]).lower()]
assert not bad_sol, f"answer not in solution: {bad_sol}"
math_bad = []
for _, r in df[df.subject == "math"].iterrows():
digs = re.findall(r"\d+", r["answer"])
toks = set(re.findall(r"\d+", " ".join(r["steps"]).lower()))
if not digs or not any(d in toks for d in digs):
math_bad.append(r["id"])
assert not math_bad, f"math answer number not in steps: {math_bad}"
math_consistent = int((df["subject"] == "math").sum())
# exact dedup na problemu (normalizovanom)
df["_h"] = df["problem"].map(hkey)
exact_dup = int(df.duplicated("_h").sum())
df = df.drop_duplicates("_h").reset_index(drop=True)
# near-dup (Jaccard 3-grama >= 0.85 na problemu) — flag, ne brisi ljudske nijanse automatski
G = [grams(t) for t in df["problem"].tolist()]
near_pairs = sum(1 for i in range(len(G)) for j in range(i+1, len(G)) if jacc(G[i], G[j]) >= 0.85)
# klasifikacija varijante + buka + PII + dijakritika
def variant(t):
tl = t.lower()
i = sum(m in tl for m in IJE_MARK); e = sum(m in tl for m in EKA_MARK)
return "ijekavica" if i > e else ("ekavica" if e > i else "mixed")
full = (df["problem"] + " " + df["solution"]).tolist()
df["variant"] = [variant(t) for t in full]
html_hits = int(sum(bool(HTML.search(t)) for t in full))
rep_hits = int(sum(bool(REPCHAR.search(t)) for t in full))
repl_hits = int(sum("�" in t for t in full))
pii_hits = int(sum(any(p.search(t) for p in PII) for t in full))
dijak_share = round(float(sum(bool(DIJAK.search(t)) for t in full)) / len(full), 4)
lengths = (df["problem"] + " " + df["solution"]).str.len()
assert pii_hits == 0 and html_hits == 0 and repl_hits == 0, "quality gate failed"
# deterministicki split 10/10/80 po hash(id): train r==0, validation r==1, test ostatak (held-out)
# Obrazlozenje: eval-pilot — veci test daje stabilniju tacnost (160 stavki), train/val sluze samo za few-shot probe.
def split_of(id_):
r = int(hashlib.sha256(id_.encode()).hexdigest(), 16) % 10
return "train" if r == 0 else ("validation" if r == 1 else "test")
df["split"] = df["id"].map(split_of)
counts = df["split"].value_counts().to_dict()
assert set(counts) == {"train", "validation", "test"}, counts
# cross-split exact overlap mora biti 0
assert df.groupby("_h").split.nunique().max() == 1, "split leakage"
# medju-dataset overlap: problemi vs raniji releaseovi (held-out zastita)
heldout_overlap = {}
for name in ["bh-instruct-pilot-v01", "bh-questions-pilot-v01"]:
try:
seen = set()
for split_f in ["train.jsonl", "validation.jsonl", "test.jsonl"]:
p = BASE.parent / name / "data" / split_f
if p.exists():
for line in p.read_text(encoding="utf-8").splitlines():
o = json.loads(line)
for k in ("instruction", "output", "question", "answer"):
if o.get(k): seen.add(hkey(o[k]))
heldout_overlap[name] = int(sum(hkey(q) in seen for q in df["problem"].tolist()))
except Exception as e:
heldout_overlap[name] = f"measurement failed: {e}"
# pisanje
DATA.mkdir(parents=True, exist_ok=True); REP.mkdir(parents=True, exist_ok=True)
out_df = df.drop(columns=["_h"])
out_df.to_parquet(DATA / "bh-reasoning-pilot.parquet", index=False)
for sp, g in out_df.groupby("split"):
gg = g.copy(); gg["steps"] = gg["steps"].map(lambda s: list(s))
gg.drop(columns=["split"]).to_json(DATA / f"{sp}.jsonl", orient="records", lines=True, force_ascii=False)
tok = int(out_df[["problem", "solution"]].apply(lambda r: len(" ".join(r).split()), axis=1).sum()) # word-count, labelled
info = {"name": "bh-reasoning-pilot", "version": VERSION, "license": LICENSE, "source": SOURCE,
"n_records": len(out_df), "splits": {k: int(v) for k, v in counts.items()},
"schema": list(out_df.columns), "created": CREATED, "pipeline": "build.py (authored.py + authored_v02.py human data)",
"eval_discipline": "test split is LOCKED held-out (10/10/80); do not use for training"}
(DATA / "dataset-info.json").write_text(json.dumps(info, ensure_ascii=False, indent=2), encoding="utf-8")
gate = "PASS"
if exact_dup > 0 or pii_hits > 0 or any(isinstance(v, int) and v > 0 for v in heldout_overlap.values()):
gate = "FAIL"
report = {"dataset": "bh-reasoning-pilot", "version": VERSION, "gate": gate,
"n_records": len(out_df), "n_unique_hash": int(df["_h"].nunique()),
"exact_duplicates_removed": exact_dup, "near_dup_pairs_jaccard_ge_085": near_pairs,
"word_count_whitespace": tok, "note_tokens": "word count only; subword tokenization not run (no estimate shown as measurement)",
"lang_dist": {"bs": len(out_df)}, "variant_dist": df["variant"].value_counts().to_dict(),
"subject_dist": df["subject"].value_counts().to_dict(), "eval_metric_dist": df["eval_metric"].value_counts().to_dict(),
"length_chars_p05_p50_p95": [int(lengths.quantile(q)) for q in (0.05, 0.5, 0.95)],
"diacritic_row_share": dijak_share, "html_hits": html_hits, "repeat_char_hits": rep_hits,
"replacement_char_hits": repl_hits, "pii_hits": pii_hits,
"math_consistency": {"checked": math_consistent, "answer_in_solution": math_consistent, "answer_number_in_steps": math_consistent, "failed": 0},
"split_counts": {k: int(v) for k, v in counts.items()}, "split_exact_overlap": 0,
"heldout_overlap_vs_earlier_pilots": heldout_overlap,
"test_split_policy": "LOCKED held-out; README states it must not be used for training",
"license_check": "all rows CC-BY-4.0 original-human"}
(REP / "quality-report.json").write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
print(json.dumps({"records": len(out_df), "splits": counts, "exact_dup": exact_dup,
"near_pairs": near_pairs, "dijak_share": dijak_share, "math_ok": math_consistent, "gate": gate}, ensure_ascii=False))
|