Datasets:
Download scripts/build.py from BH-Language-AI/bh-parallel-pilot-v01: direct link, hf CLI and curl.
- Browser
- Download file 11.1 kB
-
https://huggingface.co/datasets/BH-Language-AI/bh-parallel-pilot-v01/resolve/main/scripts/build.py
- Command line
-
hf download hf://datasets/BH-Language-AI/bh-parallel-pilot-v01/scripts/build.py
-
curl -L -o build.py https://huggingface.co/datasets/BH-Language-AI/bh-parallel-pilot-v01/resolve/main/scripts/build.py
11.1 kB
| # -*- coding: utf-8 -*- | |
| """Reproduktivni pipeline za bh-parallel-pilot-v03. CPU-only, stdlib + pandas/pyarrow. | |
| Koraci: normalize -> validate -> exact+near dedup -> classify -> split -> write -> report. | |
| Ulazi: scripts/tatoeba_pairs.json (CC-BY-2.0-FR, punih 632) + | |
| scripts/authored_original.py + authored_original_enbs.py (CC-BY-4.0, v01 val) + | |
| scripts/authored_original_v02.py (CC-BY-4.0, v02 val, en-bs balans) + | |
| scripts/authored_original_v03.py (CC-BY-4.0, v03 val, 484 en-bs + 484 bs-en, 8 novih domena). | |
| v01 ID-evi zamrznuti: 0001-0200 prvih 200 Tatoeba po hash-u, 0201-0668 v01 originali. | |
| v02 dodaje: 0669-1100 ostatak Tatoebe (432), 1101-1532 novi en-bs originali (432). | |
| v03 dodaje: 1533-2500 novi originali (968, smjer 484/484 -> konacni balans 1250/1250). | |
| Gate: FAIL (exit 1) = nejedinstven ID, null obavezna kolona, exact-dup > 0 u | |
| releaseu, cross-split presjek > 0, PII pogodak, nepoznata licenca. Inace PASS. | |
| """ | |
| import hashlib, json, re, sys, unicodedata | |
| from pathlib import Path | |
| import pandas as pd | |
| from authored_original import ORIGINALS | |
| from authored_original_enbs import ORIGINALS2 | |
| from authored_original_v02 import ORIGINALS3 | |
| from authored_original_v03 import ORIGINALS4 | |
| BASE = Path(__file__).resolve().parent.parent | |
| DATA = BASE / "data" | |
| REP = BASE / "reports" | |
| QUAR = BASE / "quarantine" | |
| VERSION = "v03" | |
| CREATED = "2026-12-01" | |
| TAT_SRC = "tatoeba-bs-en-20261201" | |
| TAT_LIC = "CC-BY-2.0-FR" | |
| ORG_SRC = "original-human-v01" | |
| ORG_LIC = "CC-BY-4.0" | |
| ORG2_SRC = "original-human-v02" | |
| ORG2_LIC = "CC-BY-4.0" | |
| ORG3_SRC = "original-human-v03" | |
| ORG3_LIC = "CC-BY-4.0" | |
| ALLOWED = {TAT_LIC, ORG_LIC, ORG2_LIC, ORG3_LIC} | |
| IJE_MARK = ["dje", "mlijeko", "vrijeme", "lijep", "bijel", "cijena", "svijet", | |
| "dijete", "mjesec", "pjesma", "čovjek", "ovdje", "gdje", "juče".replace("če", "čer")] | |
| EKA_MARK = ["devojka", "mleko", "vreme", "lep", "belo", "cena", "svet", "dete", | |
| "mesec", "pesma", "čovek", "ovde", "gde"] | |
| 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 i in range(max(0, len(s) - 2))} or {""} | |
| def jacc(a, b): | |
| return 0.0 if not a or not b else len(a & b) / len(a | b) | |
| rows = [] | |
| tat = json.loads((BASE / "scripts" / "tatoeba_pairs.json").read_text(encoding="utf-8")) | |
| tat = sorted(tat, key=lambda p: hashlib.sha256(p["tatoeba_bos_id"].encode()).hexdigest()) | |
| # Balans smjera 50/50; v01 je uzeo prvih TAT_V01_KEEP, v02 dodaje ostatak. | |
| # Redoslijed sortiranja nepromijenjen -> v01 ID-evi 0001-0200 ostaju isti. | |
| TAT_V01_KEEP = 200 | |
| n = 0 | |
| for p in tat[:TAT_V01_KEEP]: | |
| n += 1 | |
| rows.append({"id": f"BH-PAR-{n:04d}", "src_text": p["bs"], "tgt_text": p["en"], | |
| "src_lang": "bs", "tgt_lang": "en", "direction": "bs-en", | |
| "translation_quality": "human", "translator": f"tatoeba:{p['user']}", | |
| "domain": "tatoeba-mixed", "lang": "bs", "variant": None, "script": "Latn", | |
| "source": TAT_SRC, "license": TAT_LIC, "created": CREATED, | |
| "tatoeba_bos_id": p["tatoeba_bos_id"], "tatoeba_eng_id": p["tatoeba_eng_id"]}) | |
| for lst in (ORIGINALS, ORIGINALS2): | |
| for dr, dom, bs, en in lst: | |
| n += 1 | |
| src, tgt = (bs, en) if dr == "bs-en" else (en, bs) | |
| sl, tl = ("bs", "en") if dr == "bs-en" else ("en", "bs") | |
| rows.append({"id": f"BH-PAR-{n:04d}", | |
| "src_text": norm(src), "tgt_text": norm(tgt), | |
| "src_lang": sl, "tgt_lang": tl, "direction": dr, | |
| "translation_quality": "human", "translator": "BH-Language-AI contributors", | |
| "domain": dom, "lang": sl, "variant": None, "script": "Latn", | |
| "source": ORG_SRC, "license": ORG_LIC, "created": CREATED, | |
| "tatoeba_bos_id": "", "tatoeba_eng_id": ""}) | |
| # v02: ostatak Tatoebe (432, i dalje bs-en, CC-BY-2.0-FR) | |
| for p in tat[TAT_V01_KEEP:]: | |
| n += 1 | |
| rows.append({"id": f"BH-PAR-{n:04d}", "src_text": p["bs"], "tgt_text": p["en"], | |
| "src_lang": "bs", "tgt_lang": "en", "direction": "bs-en", | |
| "translation_quality": "human", "translator": f"tatoeba:{p['user']}", | |
| "domain": "tatoeba-mixed", "lang": "bs", "variant": None, "script": "Latn", | |
| "source": TAT_SRC, "license": TAT_LIC, "created": CREATED, | |
| "tatoeba_bos_id": p["tatoeba_bos_id"], "tatoeba_eng_id": p["tatoeba_eng_id"]}) | |
| # v02: novi original-human en-bs parovi (432) za balans smjera 50/50 | |
| for dr, dom, bs, en in ORIGINALS3: | |
| assert dr == "en-bs", dr | |
| n += 1 | |
| rows.append({"id": f"BH-PAR-{n:04d}", | |
| "src_text": norm(en), "tgt_text": norm(bs), | |
| "src_lang": "en", "tgt_lang": "bs", "direction": dr, | |
| "translation_quality": "human", "translator": "BH-Language-AI contributors", | |
| "domain": dom, "lang": "en", "variant": None, "script": "Latn", | |
| "source": ORG2_SRC, "license": ORG2_LIC, "created": CREATED, | |
| "tatoeba_bos_id": "", "tatoeba_eng_id": ""}) | |
| # v03: novi original-human parovi (968: 484 en-bs + 484 bs-en) za konacni balans 1250/1250 | |
| for dr, dom, bs, en in ORIGINALS4: | |
| n += 1 | |
| src, tgt = (bs, en) if dr == "bs-en" else (en, bs) | |
| sl, tl = ("bs", "en") if dr == "bs-en" else ("en", "bs") | |
| rows.append({"id": f"BH-PAR-{n:04d}", | |
| "src_text": norm(src), "tgt_text": norm(tgt), | |
| "src_lang": sl, "tgt_lang": tl, "direction": dr, | |
| "translation_quality": "human", "translator": "BH-Language-AI contributors", | |
| "domain": dom, "lang": sl, "variant": None, "script": "Latn", | |
| "source": ORG3_SRC, "license": ORG3_LIC, "created": CREATED, | |
| "tatoeba_bos_id": "", "tatoeba_eng_id": ""}) | |
| df = pd.DataFrame(rows) | |
| df["src_text"] = df["src_text"].map(norm) | |
| df["tgt_text"] = df["tgt_text"].map(norm) | |
| # validacija strukture | |
| errs = [] | |
| if not df["id"].is_unique: errs.append("duplicate ids") | |
| req = ["id", "src_text", "tgt_text", "src_lang", "tgt_lang", "direction", | |
| "translation_quality", "source", "license", "lang"] | |
| for c in req: | |
| if df[c].isna().any() or (df[c] == "").any(): errs.append(f"empty {c}") | |
| if not set(df["license"]) <= ALLOWED: errs.append("unknown license") | |
| if (df["src_text"] == "").any() or (df["tgt_text"] == "").any(): errs.append("empty text") | |
| # exact dedup na (src,tgt) par | |
| df["_h"] = (df["src_text"] + "\u0001" + df["tgt_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 na spojenom paru) — broji se, ne brise | |
| joined = (df["src_text"] + " " + df["tgt_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) | |
| # varijanta se klasifikuje na bosanskoj strani; buka + PII na obje | |
| def bs_side(r): return r["src_text"] if r["src_lang"] == "bs" else r["tgt_text"] | |
| 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") | |
| df["variant"] = df.apply(bs_side, axis=1).map(variant) | |
| full = (df["src_text"] + " " + df["tgt_text"]).tolist() | |
| 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["src_text"] + " " + df["tgt_text"]).str.len() | |
| if pii_hits or html_hits or repl_hits: errs.append("noise/PII gate") | |
| # deterministicki split 80/10/10 po hash(id) | |
| def split_of(i_): | |
| r = int(hashlib.sha256(i_.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() | |
| if set(counts) != {"train", "validation", "test"}: errs.append(f"split coverage {counts}") | |
| if df.groupby("_h").split.nunique().max() != 1: errs.append("split leakage") | |
| gate = "PASS" if not errs and exact_dup == 0 else "FAIL" | |
| # 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-parallel-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[["src_text", "tgt_text"]].apply(lambda r: len(" ".join(r).split()), axis=1).sum()) | |
| info = {"name": "bh-parallel-pilot", "version": VERSION, | |
| "licenses": sorted(out_df["license"].unique().tolist()), | |
| "sources": sorted(out_df["source"].unique().tolist()), | |
| "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 (tatoeba_pairs.json + authored_original.py + authored_original_enbs.py + authored_original_v02.py + authored_original_v03.py)"} | |
| (DATA / "dataset-info.json").write_text(json.dumps(info, ensure_ascii=False, indent=2), encoding="utf-8") | |
| bysrc = out_df.groupby(["source", "license"]).size().to_dict() | |
| report = {"dataset": "bh-parallel-pilot", "version": VERSION, "gate": gate, | |
| "gate_errors": errs, "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", | |
| "by_source_license": {f"{a} [{b}]": int(c) for (a, b), c in bysrc.items()}, | |
| "direction_dist": out_df["direction"].value_counts().to_dict(), | |
| "lang_dist": out_df["lang"].value_counts().to_dict(), | |
| "variant_dist (bs side)": df["variant"].value_counts().to_dict(), | |
| "translation_quality_dist": out_df["translation_quality"].value_counts().to_dict(), | |
| "domain_dist": out_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, | |
| "heldout_overlap": "n/a (pilot has no external held-out; test split is disjoint by id hash)", | |
| "license_check": "all rows carry a clarified license (CC-BY-2.0-FR tatoeba / CC-BY-4.0 original-human)", | |
| "contamination_between_datasets": "not yet measured (manifest hash list in dataset-info)"} | |
| (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, "by_source": {f"{a} [{b}]": int(c) for (a, b), c in bysrc.items()}, | |
| "gate": gate, "errors": errs}, ensure_ascii=False)) | |
| sys.exit(0 if gate == "PASS" else 1) | |