code-switch-mtp / scripts /phase1_data_pipeline.py
Anupam-Rawat-IITB's picture
Add code, result files and documentation
3bbd5dd verified
Raw History Blame Contribute Delete
7.84 kB
"""Phase 1 data pipeline: Hindi corpus, ITRANS reversibility, Dakshina triples and ambiguity.
Runs the four Phase 1 build steps in order and writes results/ CSVs. Halts
after step 2 if the ITRANS round-trip reversibility rate is below the
configured threshold (default 0.99) -- a lossy L2 invalidates the
fertility-ladder design, per the experiment brief, so this is a hard stop,
not a warning.
"""
import argparse
import csv
import json
import logging
import random
import sys
from pathlib import Path
import yaml
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from src.data.dakshina import build_fertility_triples, compute_romanization_ambiguity, load_native_sentences
from src.data.hindi_corpus import build_corpus
from src.data.itrans_transliterate import check_reversibility, sentence_passes_reversibility
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
logging.getLogger("httpx").setLevel(logging.WARNING)
logging.getLogger("huggingface_hub").setLevel(logging.WARNING)
logger = logging.getLogger("phase1")
def parse_args() -> argparse.Namespace:
p = argparse.ArgumentParser(description=__doc__)
p.add_argument("--config", default="configs/phase1.yaml")
return p.parse_args()
def step1_hindi_corpus(cfg: dict) -> None:
logger.info("=== step 1: hindi corpus (clean + dedup) ===")
corpus_cfg = cfg["hindi_corpus"]
stats = build_corpus(
target_tokens=corpus_cfg["target_tokens"],
out_path=corpus_cfg["out_path"],
min_chars=corpus_cfg["min_chars"],
)
logger.info(
"docs_seen=%d docs_kept=%d duplicates_dropped=%d too_short_dropped=%d token_count=%d",
stats.docs_seen, stats.docs_kept, stats.duplicates_dropped, stats.too_short_dropped, stats.token_count,
)
logger.info("wrote corpus to %s", corpus_cfg["out_path"])
with open(corpus_cfg["out_path"], encoding="utf-8") as f:
sample = [json.loads(next(f))["text"] for _ in range(3)]
for i, s in enumerate(sample):
logger.info("sample %d: %s", i, s[:200])
results_dir = Path(cfg["results_dir"])
results_dir.mkdir(parents=True, exist_ok=True)
with (results_dir / "phase1_hindi_corpus_stats.csv").open("w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow(["condition", "metric", "value", "n"])
writer.writerow(["L1_hindi_corpus", "docs_seen", stats.docs_seen, 1])
writer.writerow(["L1_hindi_corpus", "docs_kept", stats.docs_kept, 1])
writer.writerow(["L1_hindi_corpus", "duplicates_dropped", stats.duplicates_dropped, 1])
writer.writerow(["L1_hindi_corpus", "too_short_dropped", stats.too_short_dropped, 1])
writer.writerow(["L1_hindi_corpus", "token_count", stats.token_count, 1])
def step2_reversibility(cfg: dict, seed: int) -> set:
"""Measure reversibility on a sample, then filter the full sentence pool.
Returns the subset of Devanagari sentences (as a set, for O(1)
membership checks in step 3) that pass sentence_passes_reversibility --
the verified-reversible pool step 3 is restricted to. Exits the
process if the sampled rate is below threshold, since building L2 on
top of a known-lossy romanization would silently violate the
fertility ladder's "identical content" premise.
"""
logger.info("=== step 2: ITRANS reversibility check ===")
itrans_cfg = cfg["itrans"]
sentences = load_native_sentences(cfg["dakshina"]["root"])
result = check_reversibility(
sentences,
lang_code=itrans_cfg["lang_code"],
sample_size=itrans_cfg["reversibility_sample_size"],
seed=seed,
)
logger.info("reversibility: %d/%d exact matches, rate=%.4f", result.exact_matches, result.n, result.rate)
for orig, roundtripped in result.failures[:5]:
logger.info(" failure example: %r -> %r", orig, roundtripped)
results_dir = Path(cfg["results_dir"])
results_dir.mkdir(parents=True, exist_ok=True)
with (results_dir / "phase1_reversibility.csv").open("w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow(["condition", "metric", "value", "n"])
writer.writerow(["L2_itrans_roman", "reversibility_rate", result.rate, result.n])
writer.writerow(["L2_itrans_roman", "exact_matches", result.exact_matches, result.n])
min_rate = itrans_cfg["reversibility_min_rate"]
if result.rate < min_rate:
logger.error(
"REVERSIBILITY %.4f IS BELOW THE %.4f THRESHOLD. Per the experiment brief, "
"a lossy L2 invalidates the fertility-ladder design. Stopping -- do not "
"proceed to steps 3-4 or later phases until this is resolved.",
result.rate, min_rate,
)
sys.exit(1)
verified = {s for s in sentences if sentence_passes_reversibility(s, itrans_cfg["lang_code"])}
logger.info("verified-reversible subset: %d/%d full Dakshina sentences", len(verified), len(sentences))
with (results_dir / "phase1_reversibility.csv").open("a", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow(["L2_itrans_roman", "verified_subset_size", len(verified), len(sentences)])
return verified
def step3_fertility_triples(cfg: dict, allowed_sentences: set) -> None:
logger.info("=== step 3: dakshina fertility triples ===")
triples = build_fertility_triples(cfg["dakshina"]["root"], lang_code=cfg["itrans"]["lang_code"], allowed_sentences=allowed_sentences)
logger.info("built %d triples (restricted to the verified-reversible subset)", len(triples))
for t in triples[:2]:
logger.info(" devanagari: %s", t.devanagari)
logger.info(" itrans_roman: %s", t.itrans_roman)
logger.info(" natural_roman: %s", t.natural_roman)
results_dir = Path(cfg["results_dir"])
results_dir.mkdir(parents=True, exist_ok=True)
with (results_dir / "phase1_fertility_triples.csv").open("w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow(["devanagari", "itrans_roman", "natural_roman"])
for t in triples:
writer.writerow([t.devanagari, t.itrans_roman, t.natural_roman])
logger.info("wrote %d triples to results/phase1_fertility_triples.csv", len(triples))
def step4_ambiguity(cfg: dict) -> None:
logger.info("=== step 4: romanization ambiguity (H3 mechanism) ===")
stats = compute_romanization_ambiguity(cfg["dakshina"]["root"])
logger.info("n_types=%d mean_variants=%.4f", stats.n_types, stats.mean_variants)
logger.info("histogram (variant_count -> n_types): %s", sorted(stats.histogram.items()))
results_dir = Path(cfg["results_dir"])
results_dir.mkdir(parents=True, exist_ok=True)
with (results_dir / "phase1_romanization_ambiguity.csv").open("w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow(["condition", "metric", "value", "n"])
writer.writerow(["dakshina_lexicon", "n_types", stats.n_types, stats.n_types])
writer.writerow(["dakshina_lexicon", "mean_variants_per_type", stats.mean_variants, stats.n_types])
for variant_count, n_types_with_count in sorted(stats.histogram.items()):
writer.writerow(["dakshina_lexicon", f"n_types_with_{variant_count}_variants", n_types_with_count, stats.n_types])
def main() -> None:
args = parse_args()
with open(args.config, encoding="utf-8") as f:
cfg = yaml.safe_load(f)
logger.info("config: %s", cfg)
seed = cfg["seed"]
random.seed(seed)
step1_hindi_corpus(cfg)
verified_sentences = step2_reversibility(cfg, seed)
step3_fertility_triples(cfg, verified_sentences)
step4_ambiguity(cfg)
logger.info("=== PHASE 1 COMPLETE ===")
if __name__ == "__main__":
main()