code-switch-mtp / src /data /english_control.py
Anupam-Rawat-IITB's picture
Add code, result files and documentation
3bbd5dd verified
Raw History Blame Contribute Delete
4.12 kB
"""Build an English control corpus matched to Dakshina's Hindi sentence-length distribution.
E1/E2 (English subword/byte conditions) need a sentence pool comparable in
length to L1-L5's, or any measured difference could be a sentence-length
confound rather than a language/fertility effect. This streams
wikimedia/wikipedia (do not download the full dump), splits into sentences,
and samples to match the reference word-count histogram bucket-for-bucket.
"""
import re
from collections import defaultdict
from dataclasses import dataclass
from datasets import load_dataset
DATASET_NAME = "wikimedia/wikipedia"
DATASET_CONFIG = "20231101.en"
SENTENCE_SPLIT_PATTERN = re.compile(r"(?<=[.!?])\s+(?=[A-Z])")
MIN_WORDS = 3
MAX_WORDS = 80 # drop outliers before bucketing; Dakshina sentences don't run longer than this
def _word_count(sentence: str) -> int:
return len(sentence.split())
def _reference_histogram(reference_sentences: list) -> dict:
"""Bucket reference sentences by word count -> count, for proportional sampling."""
hist = defaultdict(int)
for s in reference_sentences:
n = _word_count(s)
if MIN_WORDS <= n <= MAX_WORDS:
hist[n] += 1
return hist
@dataclass
class EnglishControlStats:
"""Outcome of building the English control corpus.
Attributes:
docs_seen: Wikipedia articles streamed.
sentences_extracted: candidate sentences after splitting and length filtering.
sentences_written: sentences actually written (matched to the reference histogram).
target_n: how many sentences were requested.
"""
docs_seen: int
sentences_extracted: int
sentences_written: int
target_n: int
def build_english_control(reference_sentences: list, target_n: int, out_path: str, seed: int = 0) -> EnglishControlStats:
"""Stream English Wikipedia, split into sentences, sample to match reference word-count histogram.
Args:
reference_sentences: sentences (e.g. Dakshina's devanagari column) whose
word-count distribution this corpus should match.
target_n: total sentences to write.
out_path: destination for a single-column `text` CSV.
seed: for reproducible sampling.
"""
import csv
import random
rng = random.Random(seed)
ref_hist = _reference_histogram(reference_sentences)
ref_total = sum(ref_hist.values())
# proportional quota per word-count bucket, at least 1 for any nonzero bucket
quota = {n: max(1, round(target_n * count / ref_total)) for n, count in ref_hist.items()}
pool_by_bucket = defaultdict(list)
ds = load_dataset(DATASET_NAME, DATASET_CONFIG, split="train", streaming=True)
docs_seen = 0
sentences_extracted = 0
needed_buckets = set(quota.keys())
for row in ds:
docs_seen += 1
text = row["text"]
for sent in SENTENCE_SPLIT_PATTERN.split(text):
sent = sent.strip()
if not sent:
continue
n = _word_count(sent)
if n not in needed_buckets:
continue
sentences_extracted += 1
if len(pool_by_bucket[n]) < quota[n] * 3: # oversample a bit for variety before final sampling
pool_by_bucket[n].append(sent)
if docs_seen % 2000 == 0:
filled = sum(1 for n in needed_buckets if len(pool_by_bucket[n]) >= quota[n])
if filled == len(needed_buckets):
break
written = []
for n, q in quota.items():
candidates = pool_by_bucket.get(n, [])
take = candidates if len(candidates) <= q else rng.sample(candidates, q)
written.extend(take)
rng.shuffle(written)
written = written[:target_n]
with open(out_path, "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow(["text"])
for s in written:
writer.writerow([s])
return EnglishControlStats(
docs_seen=docs_seen,
sentences_extracted=sentences_extracted,
sentences_written=len(written),
target_n=target_n,
)