Download scripts/build.py from BH-Language-AI/bh-conversation-pilot-v01: direct link, hf CLI and curl.
- Browser
- Download file 12.6 kB
-
https://huggingface.co/datasets/BH-Language-AI/bh-conversation-pilot-v01/resolve/main/scripts/build.py
- Command line
-
hf download hf://datasets/BH-Language-AI/bh-conversation-pilot-v01/scripts/build.py
-
curl -L -o build.py https://huggingface.co/datasets/BH-Language-AI/bh-conversation-pilot-v01/resolve/main/scripts/build.py
12.6 kB
| # -*- coding: utf-8 -*- | |
| """Reproduktivni pipeline za bh-conversation-pilot-v01. CPU-only, stdlib + pandas/pyarrow. | |
| Koraci: compose -> normalize -> validate -> dedup -> classify -> split -> write -> report. | |
| Grupisano splitovanje: cijeli razgovor uvijek u jednom splitu (hash po context_id). | |
| Parquet nosi `messages` kao JSON-string (engine-kompatibilnost); JSONL ogledalo nosi listu.""" | |
| import hashlib | |
| import json | |
| import re | |
| import unicodedata | |
| from pathlib import Path | |
| import pandas as pd | |
| from authored_conv import CTX, THANKS, TOPICS | |
| from authored_conv_v02 import CTX2, TOPICS2 | |
| from authored_conv_v03 import CTX3, TOPICS3 | |
| 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" | |
| TOPIC_ORDER = ["svakodnevica", "obrazovanje", "administracija", "tehnologija", "kultura", "posao"] | |
| LENGTH_CYCLE = [2, 4, 3, 4, 5] # broj poruka; neparne duzine zavrsavaju user-zahvalom | |
| GREET = ["", "Zdravo! ", "Dobar dan! ", "Pozdrav! ", "Selam! "] | |
| 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"[čćžšđČĆŽŠĐ]") | |
| 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) | |
| def build_dialogues(n=150): | |
| convos = [] | |
| for i in range(n): | |
| topic = TOPIC_ORDER[i % len(TOPIC_ORDER)] | |
| pool = TOPICS[topic] | |
| k = i // len(TOPIC_ORDER) # redni broj dijaloga unutar teme (0..24) | |
| opener_u, opener_a = pool["openers"][(k + 3 * (k // 10)) % len(pool["openers"])] | |
| fu_u, fu_a = pool["followups"][(i // 2) % len(pool["followups"])] | |
| thanks = THANKS[i % len(THANKS)] | |
| thanks2 = THANKS[(i + 2) % len(THANKS)] | |
| greet = GREET[k % len(GREET)] | |
| ctx = CTX[topic][(k + k // 10) % len(CTX[topic])] | |
| nmsg = LENGTH_CYCLE[i % len(LENGTH_CYCLE)] | |
| u1 = norm(greet + opener_u + " " + ctx) | |
| msgs = [{"role": "user", "content": u1}, {"role": "assistant", "content": norm(opener_a)}] | |
| if nmsg >= 3: | |
| msgs.append({"role": "user", "content": norm(fu_u)}) | |
| if nmsg >= 4: | |
| msgs.append({"role": "assistant", "content": norm(fu_a)}) | |
| if nmsg >= 5: | |
| msgs.append({"role": "user", "content": norm(thanks2)}) | |
| elif nmsg == 3: | |
| msgs[-1] = {"role": "user", "content": norm(thanks)} | |
| # roles moraju alternirati user/assistant, prvi uvijek user | |
| for k, m in enumerate(msgs): | |
| assert m["role"] == ("user" if k % 2 == 0 else "assistant"), (i, k) | |
| assert m["content"], (i, k) | |
| convos.append((topic, msgs)) | |
| return convos | |
| rows = [] | |
| for i, (topic, msgs) in enumerate(build_dialogues(), 1): | |
| rows.append({ | |
| "id": f"BH-CONV-{i:04d}", | |
| "context_id": f"CTX-{i:04d}", | |
| "topic": topic, | |
| "messages": msgs, | |
| "turns": len(msgs), | |
| "lang": "bs", | |
| "variant": None, | |
| "script": "Latn", | |
| "source": SOURCE, | |
| "license": LICENSE, | |
| "created": CREATED, | |
| }) | |
| # v02 dopuna: novih 150 dijaloga (BH-CONV-0151..0300), isti obrazac, novi uvodi/konteksti. | |
| # Prvih 150 redova gore ostaje nepromijenjeno (isti id/context_id/topic/messages). | |
| for k in range(150): | |
| topic = TOPIC_ORDER[k % len(TOPIC_ORDER)] | |
| j = k // len(TOPIC_ORDER) # 0..24 redni broj novog dijaloga unutar teme | |
| pool2 = TOPICS2[topic]["openers"] | |
| fu_pool = TOPICS[topic]["followups"] | |
| opener_u, opener_a = pool2[(j + 3 * (j // 10)) % len(pool2)] | |
| fu_u, fu_a = fu_pool[((150 + k) // 2) % len(fu_pool)] | |
| thanks = THANKS[(150 + k) % len(THANKS)] | |
| thanks2 = THANKS[(150 + k + 2) % len(THANKS)] | |
| greet = GREET[j % len(GREET)] | |
| ctx = CTX2[topic][(j + j // 10) % len(CTX2[topic])] | |
| nmsg = LENGTH_CYCLE[(150 + k) % len(LENGTH_CYCLE)] | |
| u1 = norm(greet + opener_u + " " + ctx) | |
| msgs = [{"role": "user", "content": u1}, {"role": "assistant", "content": norm(opener_a)}] | |
| if nmsg >= 3: | |
| msgs.append({"role": "user", "content": norm(fu_u)}) | |
| if nmsg >= 4: | |
| msgs.append({"role": "assistant", "content": norm(fu_a)}) | |
| if nmsg >= 5: | |
| msgs.append({"role": "user", "content": norm(thanks2)}) | |
| elif nmsg == 3: | |
| msgs[-1] = {"role": "user", "content": norm(thanks)} | |
| for kk, m in enumerate(msgs): | |
| assert m["role"] == ("user" if kk % 2 == 0 else "assistant"), (150 + k, kk) | |
| assert m["content"], (150 + k, kk) | |
| i = 151 + k | |
| rows.append({ | |
| "id": f"BH-CONV-{i:04d}", | |
| "context_id": f"CTX-{i:04d}", | |
| "topic": topic, | |
| "messages": msgs, | |
| "turns": len(msgs), | |
| "lang": "bs", | |
| "variant": None, | |
| "script": "Latn", | |
| "source": SOURCE, | |
| "license": LICENSE, | |
| "created": CREATED, | |
| }) | |
| # v03 dopuna: novih 204 dijaloga (BH-CONV-0301..0504, 6 tema x 34), isti obrazac, novi uvodi/konteksti. | |
| # Prvih 300 redova gore ostaje nepromijenjeno (isti id/context_id/topic/messages). | |
| for k in range(204): | |
| topic = TOPIC_ORDER[k % len(TOPIC_ORDER)] | |
| j = k // len(TOPIC_ORDER) # 0..33 redni broj novog dijaloga unutar teme | |
| opener_u, opener_a = TOPICS3[topic]["openers"][j] | |
| fu_pool = TOPICS[topic]["followups"] | |
| fu_u, fu_a = fu_pool[((300 + k) // 2) % len(fu_pool)] | |
| thanks = THANKS[(300 + k) % len(THANKS)] | |
| thanks2 = THANKS[(300 + k + 2) % len(THANKS)] | |
| greet = GREET[j % len(GREET)] | |
| ctx = CTX3[topic][(j + j // 10) % len(CTX3[topic])] | |
| nmsg = LENGTH_CYCLE[(300 + k) % len(LENGTH_CYCLE)] | |
| u1 = norm(greet + opener_u + " " + ctx) | |
| msgs = [{"role": "user", "content": u1}, {"role": "assistant", "content": norm(opener_a)}] | |
| if nmsg >= 3: | |
| msgs.append({"role": "user", "content": norm(fu_u)}) | |
| if nmsg >= 4: | |
| msgs.append({"role": "assistant", "content": norm(fu_a)}) | |
| if nmsg >= 5: | |
| msgs.append({"role": "user", "content": norm(thanks2)}) | |
| elif nmsg == 3: | |
| msgs[-1] = {"role": "user", "content": norm(thanks)} | |
| for kk, m in enumerate(msgs): | |
| assert m["role"] == ("user" if kk % 2 == 0 else "assistant"), (300 + k, kk) | |
| assert m["content"], (300 + k, kk) | |
| i = 301 + k | |
| rows.append({ | |
| "id": f"BH-CONV-{i:04d}", | |
| "context_id": f"CTX-{i:04d}", | |
| "topic": topic, | |
| "messages": msgs, | |
| "turns": len(msgs), | |
| "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["context_id"].is_unique, "duplicate context ids" | |
| assert (df["turns"] >= 2).all() and (df["turns"] <= 5).all(), "turns out of range" | |
| assert df["messages"].map(lambda m: m[0]["role"] == "user").all(), "first must be user" | |
| assert df["messages"].map(lambda m: all(x["role"] in ("user", "assistant") for x in m)).all() | |
| joined = df["messages"].map(lambda m: " ".join(x["content"] for x in m)) | |
| df["_h"] = joined.map(hkey) | |
| exact_dup = int(df.duplicated("_h").sum()) | |
| df = df.drop_duplicates("_h").reset_index(drop=True) | |
| joined = df["messages"].map(lambda m: " ".join(x["content"] for x in m)) | |
| G = [grams(t) for t in joined] | |
| near_pairs = sum(1 for a in range(len(G)) for b in range(a + 1, len(G)) if jacc(G[a], G[b]) >= 0.85) | |
| 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 = joined.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) | |
| assert pii_hits == 0 and html_hits == 0 and repl_hits == 0, "quality gate failed" | |
| def split_of(ctx): | |
| r = int(hashlib.sha256(ctx.encode()).hexdigest(), 16) % 10 | |
| return "train" if r < 8 else ("validation" if r == 8 else "test") | |
| df["split"] = df["context_id"].map(split_of) | |
| counts = df["split"].value_counts().to_dict() | |
| assert set(counts) == {"train", "validation", "test"}, counts | |
| assert df.groupby("_h").split.nunique().max() == 1, "split leakage" | |
| assert df.groupby("context_id").split.nunique().max() == 1, "conversation split across splits" | |
| lengths = joined.str.len() | |
| msg_lens = df["messages"].map(lambda m: [len(x["content"]) for x in m]) | |
| flat_msg = [L for sub in msg_lens for L in sub] | |
| DATA.mkdir(parents=True, exist_ok=True) | |
| REP.mkdir(parents=True, exist_ok=True) | |
| df["messages_json"] = df["messages"].map(lambda m: json.dumps(m, ensure_ascii=False)) | |
| out_df = df.drop(columns=["_h", "messages"]) | |
| out_df = out_df.rename(columns={"messages_json": "messages"}) | |
| out_df.to_parquet(DATA / "bh-conversation-pilot.parquet", index=False) | |
| for sp, g in df.groupby("split"): | |
| recs = [] | |
| for _, r in g.iterrows(): | |
| d = r.drop(labels=["_h", "split"]).to_dict() | |
| recs.append(d) | |
| with open(DATA / f"{sp}.jsonl", "w", encoding="utf-8") as f: | |
| for d in recs: | |
| f.write(json.dumps(d, ensure_ascii=False) + "\n") | |
| words = joined.map(lambda t: len(t.split())).sum() | |
| topic_dist = df["topic"].value_counts().to_dict() | |
| turn_dist = df["turns"].value_counts().sort_index().to_dict() | |
| turn_dist = {int(k): int(v) for k, v in turn_dist.items()} | |
| info = {"name": "bh-conversation-pilot", "version": VERSION, "license": LICENSE, "source": SOURCE, | |
| "n_records": len(df), "splits": {k: int(v) for k, v in counts.items()}, | |
| "schema": list(out_df.columns), "created": CREATED, | |
| "note_messages": "messages je JSON-string u Parquetu (engine-kompatibilnost), lista u JSONL ogledalu", | |
| "pipeline": "build.py (authored_conv.py + authored_conv_v02.py human data)"} | |
| (DATA / "dataset-info.json").write_text(json.dumps(info, ensure_ascii=False, indent=2), encoding="utf-8") | |
| import numpy as np # noqa: E402 | |
| report = {"dataset": "bh-conversation-pilot", "version": VERSION, "gate": "PASS", | |
| "n_records": len(df), "n_dialogues": len(df), "n_unique_hash": int(df["_h"].nunique()), | |
| "exact_duplicates_removed": exact_dup, "near_dup_pairs_jaccard_ge_085": near_pairs, | |
| "total_turns_messages": int(df["turns"].sum()), "avg_turns_per_dialogue": round(float(df["turns"].mean()), 3), | |
| "turns_dist": turn_dist, | |
| "word_count_whitespace": int(words), "note_tokens": "word count only; subword tokenization not run", | |
| "lang_dist": {"bs": len(df)}, "variant_dist": df["variant"].value_counts().to_dict(), | |
| "topic_dist": topic_dist, | |
| "dialogue_length_chars_p05_p50_p95": [int(lengths.quantile(q)) for q in (0.05, 0.5, 0.95)], | |
| "message_length_chars_p05_p50_p95": [int(np.quantile(flat_msg, 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, | |
| "diacritics_share_records_with_cczzssdd": dijak_share, | |
| "split_counts": {k: int(v) for k, v in counts.items()}, "split_exact_overlap": 0, | |
| "split_unit": "context_id (cijeli razgovor uvijek u jednom splitu)", | |
| "heldout_overlap": "n/a (pilot has no external held-out; test split is disjoint by context_id hash)", | |
| "license_check": "all rows CC-BY-4.0 original-human", "contamination_between_datasets": "not yet measured (first release; manifest hash list published 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(df), "turns_total": int(df["turns"].sum()), | |
| "turns_avg": round(float(df["turns"].mean()), 3), "splits": counts, | |
| "topics": topic_dist, "turn_dist": turn_dist, "exact_dup": exact_dup, | |
| "near_pairs": near_pairs, "gate": "PASS"}, ensure_ascii=False)) | |