nawah-dialect-data / prepare_dialect.py
oddadmix's picture
Upload prepare_dialect.py with huggingface_hub
16345f4 verified
Raw History Blame Contribute Delete
5.9 kB
"""
Build a multi-class Arabic dialect + MSA classification set.
Source: oddadmix/dialectal-arabic-text-no-audio-v2 (552,421 YouTube transcript rows, 15 labels),
plus MSA articles from oddadmix/msa_texts_summaries_new chunked to transcript length.
Four decisions the raw data forces:
* `en` is dropped. Its 12,998 rows are English literary prose - 100% Latin, 0% Arabic. It is not
an Arabic dialect, it is separable by script alone, and keeping it would inflate accuracy.
* `ar` is renamed `msa`. Those 9,898 rows already *are* MSA (instructional and religious prose),
so MSA was never missing from this dataset, only under-represented at 1.8%.
* Diacritics are stripped. Their rate runs 30% (ar) to 88% (lb) and tracks the transcription
source, which maps to dialect - a model can read the diacritic density instead of the dialect.
Real-world Arabic is undiacritized anyway.
* MSA chunks are split by *article*, so no two chunks of one article straddle train and test.
Known confound, not fully fixable here: the dialect rows are speech transcripts while the added
MSA is written prose. A classifier can exploit register rather than dialect. Chunking MSA to the
dialect length distribution and stripping diacritics narrows the gap; the honest check is the
`ar`-only MSA slice, which IS from a different source than the added chunks - reported separately.
"""
import json
import os
import random
import re
import unicodedata
from collections import Counter, defaultdict
from pathlib import Path
import pyarrow.parquet as pq
from huggingface_hub import hf_hub_download
OUT = Path(os.environ.get("OUT_DIR", "data")); OUT.mkdir(exist_ok=True)
SEED = 42
MSA_TARGET = int(os.environ.get("MSA_TARGET", 50000))
CHUNK_LO, CHUNK_HI = 18, 70 # dialect words: p10 16, p50 39, p90 71
DIACRITICS = re.compile(r"[ً-ْٰـ]") # tashkeel + tatweel
def normalise(s: str) -> str:
s = unicodedata.normalize("NFKC", s or "") # folds Arabic Presentation Forms to standard
s = DIACRITICS.sub("", s)
return re.sub(r"\s+", " ", s).strip()
def load_dialects():
rows = {}
for split, fn in (("train", "data/train-00000-of-00001.parquet"),
("test", "data/test-00000-of-00001.parquet")):
t = pq.read_table(hf_hub_download("oddadmix/dialectal-arabic-text-no-audio-v2", fn,
repo_type="dataset"))
out = []
for txt, lang in zip(t.column("transcript_text").to_pylist(),
t.column("language").to_pylist()):
if lang == "en": # English prose, not a dialect
continue
lab = "msa" if lang == "ar" else lang
n = normalise(txt)
if len(n.split()) < 5:
continue
out.append({"text": n, "label": lab, "source": "transcript"})
rows[split] = out
return rows
def chunk(text, rng):
w = normalise(text).split()
out, i = [], 0
while i < len(w):
k = rng.randint(CHUNK_LO, CHUNK_HI)
piece = w[i:i + k]
if len(piece) >= CHUNK_LO:
out.append(" ".join(piece))
i += k
return out
def load_msa(n_train, n_test):
t = pq.read_table(hf_hub_download("oddadmix/msa_texts_summaries_new",
"data/train-00000-of-00001-3efb20f362aadfd6.parquet",
repo_type="dataset"))
arts = [x or "" for x in t.column("text").to_pylist()]
rng = random.Random(SEED)
idx = list(range(len(arts))); rng.shuffle(idx)
cut = int(len(idx) * 0.05)
test_arts, train_arts = idx[:cut], idx[cut:] # split by article, never by chunk
def take(article_ids, want):
out = []
for a in article_ids:
for c in chunk(arts[a], rng):
out.append({"text": c, "label": "msa", "source": "article"})
if len(out) >= want:
return out
return out
return take(train_arts, n_train), take(test_arts, n_test)
def main():
rng = random.Random(SEED)
d = load_dialects()
have_msa = sum(1 for r in d["train"] if r["label"] == "msa")
need = max(0, MSA_TARGET - have_msa)
msa_tr, msa_te = load_msa(need, 400)
train = d["train"] + msa_tr
test = d["test"] + msa_te
rng.shuffle(train)
# De-duplicate within and across splits, on normalised text.
seen, tr2 = set(), []
for r in train:
if r["text"] in seen:
continue
seen.add(r["text"]); tr2.append(r)
te2 = [r for r in test if r["text"] not in seen]
dropped_test = len(test) - len(te2)
labels = sorted({r["label"] for r in tr2})
lab2id = {l: i for i, l in enumerate(labels)}
for r in tr2 + te2:
r["label_id"] = lab2id[r["label"]]
for name, rows in (("train", tr2), ("test", te2)):
with open(OUT / f"{name}.jsonl", "w", encoding="utf-8") as fh:
for r in rows:
fh.write(json.dumps(r, ensure_ascii=False) + "\n")
json.dump({"labels": labels, "label2id": lab2id},
open(OUT / "labels.json", "w", encoding="utf-8"), ensure_ascii=False, indent=1)
print(f"dropped en; ar -> msa; MSA topped up by {len(msa_tr):,} article chunks")
print(f"train {len(tr2):,} test {len(te2):,} ({dropped_test} test rows dropped as dupes)")
print(f"labels ({len(labels)}): {labels}")
c = Counter(r["label"] for r in tr2)
for l, v in c.most_common():
print(f" {l:<5}{v:>8,} {v/len(tr2):6.1%}")
ct = Counter(r["label"] for r in te2)
print("test:", dict(ct.most_common()))
print("msa by source (train):",
dict(Counter(r['source'] for r in tr2 if r['label']=='msa')))
print("msa by source (test):",
dict(Counter(r['source'] for r in te2 if r['label']=='msa')))
if __name__ == "__main__":
main()