#!/usr/bin/env python3 """ Latin ASR Post-Processing Dataset Builder Downloads the CLTK Latin Library in memory (ZIP) and LLPSI speech dataset, normalizes text into pure classical i/u orthography, dynamically expands indeclinable Roman numerals to Latin cardinal words, extracts word tokens and casing/punctuation tags, and pushes the stratified dataset directly to Hugging Face Hub. """ import argparse import io import os import random import re import sys import unicodedata import zipfile from collections import Counter import numpy as np import requests import nltk from nltk.tokenize import sent_tokenize from tqdm import tqdm from datasets import Dataset, DatasetDict, load_dataset from sklearn.model_selection import train_test_split # Ensure NLTK tokenizers are available for resource in ["punkt", "punkt_tab"]: try: nltk.data.find(f"tokenizers/{resource}") except LookUpError: nltk.download(resource, quiet=True) # ===================================================================== # CONFIGURATION & LOOKUP DATASETS # ===================================================================== # Standard English stopwords excluding Latin false-positives ('his', 'as') ENGLISH_STOPWORDS = { # Archive, Web Infrastructure & Editorial Terms "library", "classics", "miscellany", "home", "homepage", "index", "latin", "contents", "site", "html", "http", "https", "www", "com", "org", "edu", "christian", "medieval", "neo-latin", "prepared", "proof", "read", "proof-read", "proofread", "edited", "archive", "edition", "published", "publisher", "press", "university", "translated", "transcribed", "transcription", "scanned", "text", "texts", "source", "note", "notes", "footnote", "volume", "vol", "book", "chapter", "section", "page", "pages", "line", "lines", "version", "revised", "reprinted", # High-Confidence English Function Words "the", "of", "and", "to", "you", "that", "was", "for", "on", "are", "with", "they", "this", "have", "from", "one", "had", "by", "word", "but", "not", "what", "all", "were", "we", "when", "your", "can", "said", "there", "use", "each", "which", "how", "their", "if", "will", "up", "other", "about", "out", "many", "then", "them", "these", "some", "would" } PRAENOMINA_1ST_2ND_STEMS = { "A": "Aul", "Ap": "Appi", "C": "Gai", "Cn": "Gnae", "D": "Decim", "F": "Faust", "H": "Host", "L": "Luci", "M": "Marc", "M'": "Mani", "M′": "Mani", "M’": "Mani", "Mam": "Mamerc", "N": "Numeri", "Oct": "Octavi", "P": "Publi", "Post": "Postum", "Pro": "Procul", "Q": "Quint", "S": "Spuri", "Sec": "Secund", "Seq": "Secund", "Ser": "Servi", "Sex": "Sext", "Sp": "Spuri", "St": "Stati", "T": "Tit", "Ti": "Tiberi", "V": "Vibi", "Vol": "Voles", "Vop": "Vopisc" } DECLENSION_3RD_PRAENOMINA = { "Opet": {"nom": "Opiter", "acc": "Opitrem", "gen": "Opitris", "dat": "Opitri", "abl": "Opitre"}, "Sert": {"nom": "Sertor", "acc": "Sertorem", "gen": "Sertoris", "dat": "Sertori", "abl": "Sertore"}, "Mai": {"nom": "Maio", "acc": "Maiorem", "gen": "Maioris", "dat": "Maiori", "abl": "Maiore"}, "Min": {"nom": "Mino", "acc": "Minorem", "gen": "Minoris", "dat": "Minori", "abl": "Minore"}, } PUNCT_MAP = { '': 'NONE', '.': 'PERIOD', ',': 'COMMA', ':': 'COLON', ';': 'SEMICOLON', '!': 'EXCLAMATION', '?': 'QUESTION' } ROMAN_NUMERAL_REGEX = r"^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$" # Lowercase Roman numerals that collide with real Latin vocabulary (e.g. vi -> vī = "by force"). LOWERCASE_ROMAN_EXCLUSIONS = {"i", "vi"} UNITS_4_TO_9 = { 4: "quattuor", 5: "quinque", 6: "sex", 7: "septem", 8: "octo", 9: "novem" } TEENS_AND_TENS = { 10: "decem", 11: "undecim", 12: "duodecim", 13: "tredecim", 14: "quattuordecim", 15: "quindecim", 16: "sedecim", 17: "septendecim", 18: "duodeviginti", 19: "undeviginti", 20: "viginti", 30: "triginta", 40: "quadraginta", 50: "quinquaginta", 60: "sexaginta", 70: "septuaginta", 80: "octoginta", 90: "nonaginta" } # Terminal punctuation allowed at the end of a sentence TERMINAL_PUNCTUATION = {".", "?", "!"} CLOSING_QUOTES = '"”»\'’' # Citation and editorial abbreviations whose periods should NOT trigger sentence splits SCHOLASTIC_ABBREVS = ( r"\b(Corinth|Cor|Gal|Eph|Phil|Col|Thess|Tim|Tit|Philem|Hebr|Pet|Joan|Apoc|" r"Matt|Marc|Luc|Act|Rom|Gen|Exod|Lev|Num|Deut|Jos|Judic|Reg|Paral|Esd|Tob|" r"Judith|Esth|Job|Ps|Prov|Eccl|Cant|Sap|Sir|Is|Jer|Lam|Bar|Ezech|Dan|Osee|" r"Joel|Amos|Abd|Jon|Mich|Nah|Hab|Soph|Agg|Zach|Mal|Mach|cap|v|vv|f|fol|lib|" r"p|pp|ibid|ca|seq|e\.g|i\.e|S|St|Th|q|a|art|ad|resp|dist|m|n)\." ) # ===================================================================== # EDITORIAL & METADATA FILTERING # ===================================================================== def strip_diacritics(text: str) -> str: """Strips macrons, accents, and converts ligatures (æ/œ -> ae/oe).""" text = text.replace("æ", "ae").replace("œ", "oe").replace("Æ", "Ae").replace("Œ", "Oe") nfd = unicodedata.normalize("NFD", text) filtered = "".join(c for c in nfd if unicodedata.category(c) != "Mn") return unicodedata.normalize("NFC", filtered) def strip_section_numbers(text: str) -> str: """Strips bracketed or leading section numbers e.g. [1], [1.1], 1.""" text = re.sub(r"\[\s*[\d\s.,IVXLCDM]+\s*\]", "", text) return re.sub(r"^\s*\d+\b\.?\s*", "", text) def is_editorial_or_metadata(text: str) -> bool: """Identifies editorial headnotes, dates, and apparatus criticus entries.""" clean = text.strip() if not clean: return True if re.search(r"\b(Scr|ep|epp|cod|codd|pag|v|vv|a\.u\.c|ed)\b\.", clean, re.IGNORECASE): return True if re.search(r"^\s*([ivxlcdm\d]+\s+)?(K|Kal|Nones|Non|Ibus|Id)\b", clean, re.IGNORECASE): return True return False def has_all_caps_or_unexpanded_roman(sentence: str) -> bool: """Rejects sentences containing ALL-CAPS words or unexpanded Roman numerals.""" words = re.findall(r"\b[A-Z]+\b", sentence) for w in words: if len(w) > 1 or re.match(ROMAN_NUMERAL_REGEX, w): return True return False def contains_english(text_line: str) -> bool: words = set(re.findall(r"\b[a-zA-Z]+\b", text_line.lower())) return bool(words.intersection(ENGLISH_STOPWORDS)) # ===================================================================== # LATIN NORMALIZATION & DYNAMIC ROMAN NUMERAL HELPERS # ===================================================================== def roman_to_int(roman: str) -> int: """Parses a Roman numeral string into an integer.""" roman_dict = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} total = 0 prev_val = 0 for char in reversed(roman): val = roman_dict.get(char, 0) if val < prev_val: total -= val else: total += val prev_val = val return total def int_to_indeclinable_latin(n: int) -> str | None: """ Converts an integer to Latin words ONLY if all constituent components are strictly indeclinable. Returns None if any component declines. """ if n <= 0: return None # Hundreds 200-900 decline (ducenti, trecenti, etc.) hundreds = (n % 1000) // 100 if 2 <= hundreds <= 9: return None # Thousands > 1000 use 'milia' which declines as a neuter noun thousands = n // 1000 if thousands > 1: return None parts = [] if thousands == 1: parts.append("mille") if hundreds == 1: parts.append("centum") rem = n % 100 if rem > 0: if rem in TEENS_AND_TENS: parts.append(TEENS_AND_TENS[rem]) else: tens_val = (rem // 10) * 10 unit_val = rem % 10 # Reject if units are 1, 2, or 3 (unus, duo, tres decline) if unit_val in (1, 2, 3) or tens_val not in TEENS_AND_TENS or unit_val not in UNITS_4_TO_9: return None parts.append(f"{TEENS_AND_TENS[tens_val]} {UNITS_4_TO_9[unit_val]}") return " ".join(parts) if parts else None def expand_safe_roman_numerals(text: str) -> str: """ Dynamically converts valid indeclinable Roman numerals (upper and safe lower) to Latin cardinal words. """ def replacer(match): token = match.group(0) # 1. Protect real Latin words that look like lowercase Roman numerals if token.islower() and token in LOWERCASE_ROMAN_EXCLUSIONS: return token upper_token = token.upper() # 2. Validate Roman numeral syntax (e.g. XIV is valid, VICI is not) if not re.match(ROMAN_NUMERAL_REGEX, upper_token): return token # 3. Convert and check if grammatically indeclinable val = roman_to_int(upper_token) latin_words = int_to_indeclinable_latin(val) if latin_words is None: return token # 4. Preserve matching casing if token.isupper(): return latin_words.upper() elif token.istitle(): return latin_words.capitalize() else: return latin_words.lower() # Match tokens consisting entirely of Roman numeral characters (case-insensitive) return re.sub(r"\b[a-zA-Z]+\b", replacer, text) def inflect_praenomen(abbrev: str, next_word: str) -> str | None: clean_abbrev = abbrev.rstrip(".") target = next_word.lower() if clean_abbrev == "Agr": if target.endswith("am"): return "Agrippam" if target.endswith("ae"): return "Agrippae" return "Agrippa" if clean_abbrev in DECLENSION_3RD_PRAENOMINA: rules = DECLENSION_3RD_PRAENOMINA[clean_abbrev] if target.endswith(("em", "am", "um")): return rules["acc"] if target.endswith("is"): return rules["gen"] if target.endswith("i"): return rules["dat"] if target.endswith("e"): return rules["abl"] return rules["nom"] if clean_abbrev in PRAENOMINA_1ST_2ND_STEMS: stem = PRAENOMINA_1ST_2ND_STEMS[clean_abbrev] if target.endswith("am"): suffix = "am" elif target.endswith(("um", "em")): suffix = "um" elif target.endswith("ae"): suffix = "ae" elif target.endswith(("i", "is")): suffix = "i" elif target.endswith(("o", "e")): suffix = "o" elif target.endswith("a") and not target.endswith("ma"): suffix = "a" else: suffix = "us" return stem + suffix return None def expand_praenomina(text: str) -> str: pattern = r"\b([A-Z][a-z]{0,3}['′’]?)\.\s+([A-Z][a-z]+)" def replacer(match): abbrev, next_word = match.group(1), match.group(2) expanded = inflect_praenomen(abbrev, next_word) if expanded is None: return match.group(0) return f"{expanded} {next_word}" return re.sub(pattern, replacer, text) def normalize_iu(text: str) -> str: """ Normalizes Latin text to standard classical i/u orthography: - uva -> uua, virgo -> uirgo, jam -> iam. - Compound -iacere forms: ejicio -> eicio, conjicio -> conicio, objicit -> obicit. """ # 1. Handle compound verbs from -iacere (-jic- / -jici- after prefix/vowel -> -ic- / -ici-) text = re.sub(r'([a-zA-Z])j[iI]', r'\1i', text) text = re.sub(r'([a-zA-Z])J[iI]', r'\1I', text) # 2. Target only compound -iic- verb forms (eiicio -> eicio) text = re.sub(r'([aeiouAEIOU])ii([cC])', r'\1i\2', text) # 3. Convert all remaining J/j to I/i text = text.replace('j', 'i').replace('J', 'I') # 4. Convert all V/v to U/u text = text.replace('v', 'u').replace('V', 'U') return text def clean_punctuation(text: str) -> str: cleaned = re.sub(r"[^\w\s.,?!:;]", "", text) cleaned = re.sub(r"\s+([.,?!:;])", r"\1", cleaned) return re.sub(r"\s+", " ", cleaned).strip() def mask_citation_periods(text: str) -> tuple[str, dict[str, str]]: """Masks periods in citation abbreviations so NLTK sent_tokenize ignores them.""" placeholder_map = {} def repl(match): key = f"__ABBR_{len(placeholder_map)}__" placeholder_map[key] = match.group(0) return key masked_text = re.sub(SCHOLASTIC_ABBREVS, repl, text, flags=re.IGNORECASE) return masked_text, placeholder_map def unmask_citation_periods(text: str, placeholder_map: dict[str, str]) -> str: """Restores original citation abbreviations after sentence splitting.""" for key, orig in placeholder_map.items(): text = text.replace(key, orig) return text def is_valid_sentence(sentence_text: str) -> bool: text = sentence_text.strip() if not text or len(text.split()) < 3: return False # Strip trailing quotes using the constant core_text = text.rstrip(CLOSING_QUOTES) if not core_text or core_text[-1] not in TERMINAL_PUNCTUATION: return False if has_all_caps_or_unexpanded_roman(text): return False return True def capitalize_first_letter(s: str) -> str: """Capitalizes the first alphabetic character in the string, skipping leading punctuation/whitespace.""" for i, char in enumerate(s): if char.isalpha(): return s[:i] + char.upper() + s[i + 1 :] return s def normalize_sentence(sentence: str) -> str: text = sentence.strip() text = strip_diacritics(text) text = normalize_iu(text) text = clean_punctuation(text) if not text: return "" # Ensure sentence ends in true terminal punctuation if text[-1] not in TERMINAL_PUNCTUATION: text += "." # Force the first actual letter to uppercase return capitalize_first_letter(text) # ===================================================================== # CORPUS PROCESSING & TOKEN EXTRACTION # ===================================================================== def process_latin_corpus( raw_text: str, max_merge_len: int = 1000, p_merge: float = 0.50 ) -> str: raw_paragraphs = re.split(r"\n\s*\n+", raw_text.strip()) cleaned_paragraphs = [] for block in raw_paragraphs: lines = [line.strip() for line in block.splitlines() if line.strip()] if not lines: continue single_line_paragraph = " ".join(lines) # 1. Strip diacritics and ligatures early prep_paragraph = strip_diacritics(single_line_paragraph) if contains_english(prep_paragraph) or is_editorial_or_metadata(prep_paragraph): continue # 2. Strip section numbers, expand praenomina & expand safe Roman numerals prep_paragraph = strip_section_numbers(prep_paragraph) prep_paragraph = expand_praenomina(prep_paragraph) prep_paragraph = expand_safe_roman_numerals(prep_paragraph) raw_sentences = sent_tokenize(prep_paragraph) valid_normalized_sentences = [] for sentence_str in raw_sentences: sentence_clean = sentence_str.strip() if is_valid_sentence(sentence_clean) and not is_editorial_or_metadata(sentence_clean): norm_sent = normalize_sentence(sentence_clean) if norm_sent: valid_normalized_sentences.append(norm_sent) if valid_normalized_sentences: merged = [] current = valid_normalized_sentences[0] for nxt in valid_normalized_sentences[1:]: if len(current) + 1 + len(nxt) <= max_merge_len and random.random() < p_merge: current = f"{current} {nxt}" else: merged.append(current) current = nxt merged.append(current) cleaned_paragraphs.append("\n\n".join(merged)) return "\n\n".join(cleaned_paragraphs) def build_latin_dataset(limit_files=None) -> dict[str, list[str]]: """Downloads the CLTK repo as an in-memory ZIP archive and processes text files.""" zip_url = "https://github.com/cltk/lat_text_latin_library/archive/refs/heads/master.zip" print("Downloading CLTK Latin Library archive into RAM...") response = requests.get(zip_url) response.raise_for_status() dataset = {} with zipfile.ZipFile(io.BytesIO(response.content)) as z: txt_files = [f for f in z.namelist() if f.endswith(".txt")] if limit_files is not None: txt_files = txt_files[:limit_files] print(f"Processing {len(txt_files)} files from memory...") for file_path in tqdm(txt_files): with z.open(file_path) as f: raw_text = f.read().decode("utf-8", errors="ignore") cleaned_text = process_latin_corpus(raw_text) sentences = [s.strip() for s in cleaned_text.splitlines() if s.strip()] if sentences: dataset[file_path] = sentences return dataset def extract_token_features(text: str) -> dict[str, list[str]]: pattern = r'([A-Za-z]+)([\.,:;!\?]?)' matches = re.findall(pattern, text) tokens = [] tags = [] for word, punct in matches: if not word: continue casing = "TITLE" if word[0].isupper() else "LOWER" p_label = PUNCT_MAP.get(punct, 'NONE') tokens.append(word.lower()) tags.append(f"{casing}_{p_label}") return {"tokens": tokens, "tags": tags} # ===================================================================== # MAIN PIPELINE # ===================================================================== def main(): parser = argparse.ArgumentParser(description="Compile and push normalized Latin ASR post-processing dataset.") parser.add_argument("--repo-id", type=str, default="njand/latin-asr-post-processing-dataset", help="Hugging Face repo ID") parser.add_argument("--limit-files", type=int, default=None, help="Limit number of CLTK files processed (for testing)") parser.add_argument("--test-ratio", type=float, default=0.05, help="Test split ratio") parser.add_argument("--seed", type=int, default=42, help="Random seed") parser.add_argument("--no-push", action="store_true", help="Do not push dataset to Hugging Face Hub") args = parser.parse_args() np.random.seed(args.seed) random.seed(args.seed) # 1. Download & Process CLTK Corpus in RAM latin_dataset = build_latin_dataset(limit_files=args.limit_files) # 2. Load & Process LLPSI Speech Dataset print("Loading and normalizing LLPSI speech dataset...") llpsi_ds = load_dataset("njand/llpsi-speech-dataset", split="train", columns=["text"]) llpsi_sents = [normalize_sentence(row["text"]) for row in llpsi_ds if row.get("text")] latin_dataset["llpsi"] = llpsi_sents # 3. Extract Tokens and Casing/Punctuation Tags print("Extracting token features and target tags...") structured_data = [] for source, sentences in tqdm(latin_dataset.items()): for sentence in sentences: features = extract_token_features(sentence) if features["tokens"]: structured_data.append({ "source": source, "tokens": features["tokens"], "tags": features["tags"] }) total_tokens = sum(len(item["tokens"]) for item in structured_data) print(f"Total samples (lines): {len(structured_data):,}") print(f"Total tokens: {total_tokens:,}") # 4. Stratified Train/Test Split (handling singletons) source_counts = Counter(item["source"] for item in structured_data) stratifiable_items = [] stratifiable_labels = [] train_data = [] test_data = [] for item in structured_data: source = item["source"] if source_counts[source] < 2: if np.random.rand() < args.test_ratio: test_data.append(item) else: train_data.append(item) else: stratifiable_items.append(item) stratifiable_labels.append(source) strat_train, strat_test = train_test_split( stratifiable_items, test_size=args.test_ratio, random_state=args.seed, stratify=stratifiable_labels ) train_data.extend(strat_train) test_data.extend(strat_test) print(f"Train size: {len(train_data):,} samples | Test size: {len(test_data):,} samples") # 5. Build HF DatasetDict dataset_dict = DatasetDict({ "train": Dataset.from_list(train_data), "test": Dataset.from_list(test_data) }) # 6. Push to Hugging Face Hub if not args.no_push: print(f"Uploading dataset to Hugging Face Hub: {args.repo_id}") dataset_dict.push_to_hub(args.repo_id, private=False) print("Upload complete!") else: print("Skipping Hub upload (--no-push flag active).") if __name__ == "__main__": main()