File size: 20,897 Bytes
6c2380d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
#!/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()