#!/usr/bin/env python # -*- coding: utf-8 -*- """ Build script for NAMAA-Space/alexandria-backtranslated-pairs ================================================================= Turns a monolingual dialectal Arabic corpus into synthetic English -> dialectal Arabic training pairs: clean the Arabic, translate it to English with NLLB, then flip the direction so the machine English is the source and the authentic Arabic is the target. This is the exact recipe of the original Colab notebook (`AlexandriaX_NB1_Preprocessing.ipynb`, Phase 1 + the back-translation phase), extracted into a single runnable file. It produced the released 348,787 rows from 358,483 cleaned sentences (the difference is the 50,000-per-dialect cap biting on SA and SY). pip install transformers torch pandas tqdm python build_backtranslated_pairs.py --input unified_monolingual.csv --out bt_pairs.jsonl Input: a CSV with at least `text` and `dialect` columns (`source` and `data_type` are carried through if present). Output: JSONL rows with prompt / response / country / conv_id / turn_order, appended incrementally so an interrupted run resumes by conv_id. !! Read the two documented biases at the bottom of this file before reusing the recipe. Author: NAMAA Community (Fatimah Emad Eldin, Omer Nacar, Khloud Al Jallad, Mona Abdelazim) License: CC-BY-NC-4.0 - the source corpora and NLLB both carry their own terms """ import argparse import hashlib import html import json import os import re import unicodedata import pandas as pd from tqdm import tqdm # -------------------------------------------------------------------------------------- # Cleaning configuration - the released dataset's exact values # -------------------------------------------------------------------------------------- MIN_CHARS, MAX_CHARS = 3, 1000 MIN_WORDS = 1 MIN_ARABIC_RATIO = 0.50 # applied AFTER Latin removal, so in practice it drops # only rows with no Arabic letters at all REMOVE_DIACRITICS = False # keep dialectal orthography REMOVE_LATIN_TOKENS = True # strip embedded Latin words entirely <- see BIAS 1 below ARABIC_RANGES = r"؀-ۿݐ-ݿࢠ-ࣿﭐ-﷿ﹰ-" ARABIC_LETTER = re.compile(f"[{ARABIC_RANGES}]") LATIN_LETTER = re.compile(r"[A-Za-z]") URL_RE = re.compile(r"https?://\S+|www\.\S+") MENTION_RE = re.compile(r"@\w+") HASHTAG_RE = re.compile(r"#\w+") # removes the whole hashtag, not just '#' TIMESTAMP_RE = re.compile(r"\b\d{1,2}:\d{2}(?::\d{2})?(?:\s?[aApP][mM])?\b") TATWEEL = "ـ" TASHKEEL_RE = re.compile(r"[ؗ-ًؚ-ْٰۖ-ۭ]") EMOJI_RE = re.compile("[" "\U0001F000-\U0001FAFF\U00002600-\U000027BF\U0001F1E6-\U0001F1FF" "\U00002190-\U000021FF\U00002B00-\U00002BFF\U0000FE00-\U0000FE0F" "\U00002300-\U000023FF" "]+", flags=re.UNICODE) PUNCT_RE = re.compile(r"[_/\\~@#$%^&*()\-+=\[\]{}|;:\"'<>,.?]") # <- see BIAS 2 below # -------------------------------------------------------------------------------------- # Back-translation configuration # -------------------------------------------------------------------------------------- NLLB_MODEL = "facebook/nllb-200-distilled-600M" # the 600M distilled model, not the 1.3B BT_PER_DIALECT = 50_000 # cap per variety; this is why SA and SY sit at exactly 50,000 BATCH_SIZE = 256 # sized for an L4 MAX_SRC_TOKENS = 128 # source truncation MAX_NEW_TOKENS = 128 # greedy decoding, no beams TARGET_LANG = "eng_Latn" # Source-side (dialect) codes for the Arabic -> English direction. Note these differ from the # codes used to fine-tune NLLB for the forward direction: here LY and SD get their own codes, # while OM and MR fall back to MSA. NLLB_SRC = {"EG": "arz_Arab", "MA": "ary_Arab", "TN": "aeb_Arab", "LY": "ayl_Arab", "SD": "apd_Arab", "SA": "ars_Arab", "YE": "acq_Arab", "OM": "arb_Arab", "JO": "ajp_Arab", "LB": "apc_Arab", "SY": "apc_Arab", "PS": "ajp_Arab", "MR": "arb_Arab"} FALLBACK_SRC = "arb_Arab" # DZ and anything unlisted # -------------------------------------------------------------------------------------- # Cleaning # -------------------------------------------------------------------------------------- def arabic_ratio(s): a = len(ARABIC_LETTER.findall(s)) l = len(LATIN_LETTER.findall(s)) return a / max(1, a + l) def clean_text(s): if not isinstance(s, str): return "" s = html.unescape(s) s = URL_RE.sub(" ", s) s = MENTION_RE.sub(" ", s) s = HASHTAG_RE.sub(" ", s) s = TIMESTAMP_RE.sub(" ", s) s = EMOJI_RE.sub(" ", s) s = s.replace(TATWEEL, "") s = re.sub(r"(.)\1{2,}", r"\1", s) # collapse keyboard smashing: 3+ repeats -> 1 if REMOVE_DIACRITICS: s = TASHKEEL_RE.sub("", s) if REMOVE_LATIN_TOKENS: s = LATIN_LETTER.sub("", s) # BIAS 1 s = PUNCT_RE.sub(" ", s) # BIAS 2 s = unicodedata.normalize("NFKC", s) return re.sub(r"\s+", " ", s).strip() def norm_key(s): """Near-duplicate key: diacritics stripped, whitespace removed, lowercased.""" return re.sub(r"\s+", "", TASHKEEL_RE.sub("", s)).lower() def clean_corpus(df): before = len(df) df = df.copy() df["clean_text"] = df["text"].map(clean_text) df = df[df["clean_text"].str.len().between(MIN_CHARS, MAX_CHARS)] df = df[df["clean_text"].str.split().map(len) >= MIN_WORDS] df = df[df["clean_text"].map(arabic_ratio) >= MIN_ARABIC_RATIO] df["_k"] = df["clean_text"].map(norm_key) df = df.drop_duplicates(subset=["_k", "dialect"]).drop(columns=["_k"]).reset_index(drop=True) print(f"[clean] kept {len(df):,} / {before:,} rows") print("[clean] per dialect:", dict(sorted(df["dialect"].value_counts().items()))) return df # -------------------------------------------------------------------------------------- # Prompt rendering - identical to the supervised training prompt, with placeholder metadata # -------------------------------------------------------------------------------------- def build_prompt(country, sentence): return (f"You are an expert translator. Translate the English sentence into {country}.\n\n" f"### Metadata:\n- Country: {country}\n- Domain: Everyday / Social\n" f"- Participants: Unknown Participants\n- Speaker: A\n" f"- Speaker Direction: Unknown\n\n" f"### Conversation History:\nNo previous turns (Start of conversation).\n\n" f"### Sentence to Translate:\n{sentence.strip()}\n\n### Translation:\n") # -------------------------------------------------------------------------------------- # Back-translation # -------------------------------------------------------------------------------------- def back_translate(df, out_path, per_dialect=BT_PER_DIALECT, batch_size=BATCH_SIZE): import torch from transformers import AutoModelForSeq2SeqLM, AutoTokenizer if not torch.cuda.is_available(): raise RuntimeError("a GPU is required for back-translation") tok = AutoTokenizer.from_pretrained(NLLB_MODEL) model = AutoModelForSeq2SeqLM.from_pretrained( NLLB_MODEL, torch_dtype=torch.float16).to("cuda").eval() eng_id = tok.convert_tokens_to_ids(TARGET_LANG) done = set() if os.path.exists(out_path): # resume by conv_id with open(out_path, encoding="utf-8") as fh: for line in fh: try: done.add(json.loads(line)["conv_id"]) except Exception: pass print(f"[resume] {len(done)} pairs already written") added = 0 with open(out_path, "a", encoding="utf-8") as sink: for dialect, group in df.groupby("dialect"): rows = group["clean_text"].tolist()[:per_dialect] src_code = NLLB_SRC.get(dialect, FALLBACK_SRC) pending = [] for text in rows: cid = f"BT-{dialect}-{hashlib.md5(text.encode()).hexdigest()[:8]}" if cid not in done: pending.append((cid, text)) if not pending: continue for i in tqdm(range(0, len(pending), batch_size), desc=f"BT {dialect}"): batch = pending[i:i + batch_size] tok.src_lang = src_code enc = tok([b[1] for b in batch], return_tensors="pt", padding=True, truncation=True, max_length=MAX_SRC_TOKENS).to("cuda") with torch.no_grad(): out = model.generate(**enc, forced_bos_token_id=eng_id, max_new_tokens=MAX_NEW_TOKENS, max_length=None) english = tok.batch_decode(out, skip_special_tokens=True) for (cid, arabic), en in zip(batch, english): if not en.strip() or not arabic.strip(): continue sink.write(json.dumps({"prompt": build_prompt(dialect, en), "response": arabic, "country": dialect, "conv_id": cid, "turn_order": 1}, ensure_ascii=False) + "\n") sink.flush() added += 1 print(f"[done] wrote {added} new pairs -> {out_path}") def main(): ap = argparse.ArgumentParser() ap.add_argument("--input", required=True, help="CSV with `text` and `dialect` columns (the unified monolingual corpus)") ap.add_argument("--out", default="backtranslation_pairs.jsonl") ap.add_argument("--per-dialect", type=int, default=BT_PER_DIALECT) ap.add_argument("--batch-size", type=int, default=BATCH_SIZE) ap.add_argument("--clean-only", action="store_true", help="Run the cleaning pass and stop (no GPU needed)") args = ap.parse_args() df = clean_corpus(pd.read_csv(args.input)) if args.clean_only: return back_translate(df, args.out, per_dialect=args.per_dialect, batch_size=args.batch_size) if __name__ == "__main__": main() # ====================================================================================== # TWO DOCUMENTED BIASES - read before reusing this recipe # ====================================================================================== # BIAS 1 - Latin script is DELETED, not merely filtered. # REMOVE_LATIN_TOKENS=True strips every A-Za-z character from the Arabic before # back-translation, so no synthetic target contains a single Latin token. AlexandriaX gold # references do the opposite: 33.8% of Moroccan and 39.1% of Tunisian gold turns carry # Latin-script French or English borrowings. Training on this data therefore pushes a model # AWAY from the reference style of exactly the varieties the augmentation was meant to help. # Note also that arabic_ratio() runs after this strip, so the 0.5 threshold no longer # filters code-switched rows - it only drops rows left with no Arabic at all. # # BIAS 2 - punctuation is removed from the targets. # PUNCT_RE blanks out _ / \ ~ @ # $ % ^ & * ( ) - + = [ ] { } | ; : " ' < > , . ? # so synthetic targets lose sentence-final periods, commas and question marks (ASCII "!" # and the Arabic "؟" happen to survive, which makes the loss inconsistent rather than clean), # while the English prompts (straight from NLLB) are fully punctuated. A model trained on # this mixture learns to drop terminal punctuation, which costs character-level n-gram # credit against punctuated references. # # Both are cheap to change: set REMOVE_LATIN_TOKENS=False, and narrow PUNCT_RE to the # characters you actually want gone. Neither was changed for the released dataset, so the # published rows carry both.