admiragic's picture
Upload folder using huggingface_hub
11f115d verified
Raw History Blame Contribute Delete
7.68 kB
# -*- coding: utf-8 -*-
"""Reproduktivni pipeline za bh-questions-pilot-v01. CPU-only, stdlib + pandas/pyarrow.
Koraci: normalize -> validate -> dedup -> classify -> split -> write -> report.
EVAL DISCIPLINA: test split je zakljucan held-out i ne koristi se za trening."""
import hashlib, json, re, unicodedata
from pathlib import Path
import pandas as pd
from authored import QUESTIONS as V01_QUESTIONS
from authored_v02 import NEW_QUESTIONS as V02_QUESTIONS
from authored_v03 import NEW_QUESTIONS_V03 as V03_QUESTIONS
QUESTIONS = V01_QUESTIONS + V02_QUESTIONS + V03_QUESTIONS
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", "pjesma"]
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"}
def norm(s): return unicodedata.normalize("NFC", s.strip())
def hkey(s): return hashlib.sha256(norm(s).lower().encode()).hexdigest()
def grams(s, n=3):
s = re.sub(r"\s+", " ", norm(s).lower())
return {s[i:i+n] for n in [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, (qt, dom, q, a, ch, metric) in enumerate(QUESTIONS, 1):
rows.append({"id": f"BH-QA-{i:04d}", "question": norm(q), "answer": norm(a),
"choices": [norm(c) for c in ch] if ch else None,
"eval_metric": metric, "qtype": qt, "domain": dom, "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[["question", "answer"]] != "").all().all(), "empty required field"
assert set(df["eval_metric"]) <= {"exact_match", "human_judgement"}, "bad metric"
assert set(df["license"]) <= ALLOWED_LICENSES, "unknown license"
mc = df[df["qtype"] == "mc"]
assert (mc["choices"].map(lambda c: isinstance(c, list) and len(c) >= 3)).all(), "MC needs >=3 choices"
assert all(r["answer"] in (r["choices"] or []) for _, r in mc.iterrows()), "MC answer must be one of choices"
# exact dedup na pitanju (normalizovanom)
df["_h"] = df["question"].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 pitanju) — flag, ne brisi ljudske nijanse automatski
G = [grams(t) for t in df["question"].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["question"] + " " + df["answer"]).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["question"] + " " + df["answer"]).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)
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: pitanja vs raniji releaseovi (held-out zastita)
heldout_overlap = "not measured (no earlier release manifest found)"
ins_test = BASE.parent / "bh-instruct-pilot-v01" / "data" / "test.jsonl"
try:
if ins_test.exists():
seen = set()
for split_f in ["train.jsonl", "validation.jsonl", "test.jsonl"]:
p = BASE.parent / "bh-instruct-pilot-v01" / "data" / split_f
if p.exists():
for line in p.read_text(encoding="utf-8").splitlines():
o = json.loads(line)
seen.add(hkey((o.get("instruction") or "") + "\u0001" + (o.get("output") or "")))
heldout_overlap = int(sum(hkey(q) in seen for q in df["question"].tolist()))
except Exception as e:
heldout_overlap = 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-questions-pilot.parquet", index=False)
for sp, g in out_df.groupby("split"):
g.drop(columns=["split"]).to_json(DATA / f"{sp}.jsonl", orient="records", lines=True, force_ascii=False)
tok = int(out_df[["question", "answer"]].apply(lambda r: len(" ".join(r).split()), axis=1).sum()) # word-count, labelled
info = {"name": "bh-questions-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 human data)",
"eval_discipline": "test split is LOCKED held-out; 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 heldout_overlap != 0 and isinstance(heldout_overlap, int) and heldout_overlap > 0:
gate = "FAIL"
report = {"dataset": "bh-questions-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(),
"qtype_dist": df["qtype"].value_counts().to_dict(), "domain_dist": df["domain"].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,
"split_counts": {k: int(v) for k, v in counts.items()}, "split_exact_overlap": 0,
"heldout_overlap_vs_instruct_pilot": 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, "gate": gate}, ensure_ascii=False))