admiragic's picture
Upload folder using huggingface_hub
f9a3797 verified
Raw History Blame Contribute Delete
7.67 kB
# -*- coding: utf-8 -*-
"""Reproduktivni pipeline za bh-guard-pilot-v01. CPU-only, stdlib + pandas/pyarrow.
Koraci: normalize -> validate -> dedup -> classify -> split -> write -> report.
Profil: Classification (text, label, label_set_version) + domain."""
import hashlib, json, re, unicodedata
from pathlib import Path
import pandas as pd
from authored import EXAMPLES
BASE = Path(__file__).resolve().parent.parent
DATA = BASE / "data"
REP = BASE / "reports"
VERSION = "v03"
LABEL_SET = "v01 (3 labele)"
LABELS = ("safe", "prompt_injection", "unsafe_request")
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,}")
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, (lb, dom, tx) in enumerate(EXAMPLES, 1):
rows.append({"id": f"BH-GRD-{i:04d}", "text": norm(tx), "label": lb,
"label_set_version": LABEL_SET, "domain": dom, "lang": "bs",
"variant": None, "script": "Latn", "source": SOURCE, "license": LICENSE, "created": CREATED})
df = pd.DataFrame(rows)
# validacija strukture + label set
assert df["id"].is_unique, "duplicate ids"
assert (df[["text", "label"]] != "").all().all(), "empty required field"
assert set(df["label"].unique()) <= set(LABELS), f"unknown label: {set(df['label'].unique()) - set(LABELS)}"
assert (df["label_set_version"] == LABEL_SET).all(), "label_set_version mismatch"
assert (df["license"] == LICENSE).all(), "license mismatch"
# exact dedup na tekstu
df["_h"] = df["text"].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) — flag, ne brisi ljudske nijanse automatski
joined = df["text"].tolist()
G = [grams(t) for t in joined]
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
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["text"].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))
lengths = df["text"].str.len()
assert pii_hits == 0 and html_hits == 0 and repl_hits == 0, "quality gate failed"
# deterministicki split 80/10/10 po hash(id) — bez curenja (disjunktni ID-evi)
def split_of(id_):
r = int(hashlib.sha256(id_.encode()).hexdigest(), 16) % 10
return "train" if r < 8 else ("validation" if r == 8 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 dedup: hash protiv manifesta ranijih releasea
heldout_overlap = {}
for pilot_dir in sorted((BASE.parent).glob("*/data/*.parquet")):
if "guard" in str(pilot_dir):
continue
try:
other = pd.read_parquet(pilot_dir)
col = next((c for c in ("instruction", "text", "question", "problem", "src_text", "term") if c in other.columns), None)
if col is None and "messages" in other.columns:
import json as _json
texts = []
for m in other["messages"]:
try:
msgs = _json.loads(m) if isinstance(m, str) else m
texts.append(" ".join(x.get("content", "") for x in msgs))
except Exception:
texts.append(str(m))
oh = set(pd.Series(texts).map(hkey))
heldout_overlap[pilot_dir.parent.parent.name] = int(df["_h"].isin(oh).sum())
continue
if col is None:
continue
oh = set(other[col].map(hkey))
heldout_overlap[pilot_dir.parent.parent.name] = int(df["_h"].isin(oh).sum())
except Exception as e:
heldout_overlap[pilot_dir.parent.parent.name] = f"unreadable: {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-guard-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["text"].apply(lambda s: len(str(s).split())).sum()) # word-count, labelled
info = {"name": "bh-guard-pilot", "version": VERSION, "license": LICENSE, "source": SOURCE,
"label_set": LABEL_SET, "labels": list(LABELS),
"n_records": len(out_df), "splits": {k: int(v) for k, v in counts.items()},
"label_counts": out_df["label"].value_counts().to_dict(),
"schema": list(out_df.columns), "created": CREATED, "pipeline": "build.py (authored.py human data)"}
(DATA / "dataset-info.json").write_text(json.dumps(info, ensure_ascii=False, indent=2), encoding="utf-8")
label_split = out_df.groupby(["label", "split"]).size().unstack(fill_value=0).to_dict()
gate = "PASS" if (exact_dup == 0 and pii_hits == 0 and html_hits == 0 and repl_hits == 0
and all(v == 0 for v in heldout_overlap.values() if isinstance(v, int))) else "PASS_WITH_NOTES"
report = {"dataset": "bh-guard-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(),
"label_dist": out_df["label"].value_counts().to_dict(), "label_set_version": LABEL_SET,
"label_split_counts": {str(k): {str(kk): int(vv) for kk, vv in v.items()} for k, v in label_split.items()},
"domain_dist": df["domain"].value_counts().to_dict(),
"length_chars_p05_p50_p95": [int(lengths.quantile(q)) for q in (0.05, 0.5, 0.95)],
"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,
"cross_dataset_exact_overlap": heldout_overlap,
"heldout_overlap": "test split is disjoint by id hash; cross-dataset overlap in cross_dataset_exact_overlap",
"license_check": "all rows CC-BY-4.0 original-human", "contamination_between_datasets": "measured (see cross_dataset_exact_overlap)"}
(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, "cross_overlap": heldout_overlap, "gate": gate}, ensure_ascii=False))