LFM2-ColBERT-350M / eruu /split_eruu.py
bolorjinbat's picture
Add files using upload-large-folder tool
06e5009 verified
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import re
from pathlib import Path
# 1) Input file and output folder
INPUT_FILE = "/home/astgpu3/workspace/bolorjinbat/LFM2-ColBERT-350M/eruu/eruu.txt"
OUTPUT_DIR = "/home/astgpu3/workspace/bolorjinbat/LFM2-ColBERT-350M/Eruu_huulis"
# 2) Robust regex for Mongolian chapter headings (handles UPPER/lower, with/without spaces)
# Matches lines like "НЭГДҮГЭЭР БҮЛЭГ", "АРВАН НЭГДҮГЭЭР БҮЛЭГ", "ХОРИН ДӨРӨВДҮГЭЭР БҮЛЭГ", "ГУЧДУГААР БҮЛЭГ", etc.
chapter_ordinal = (
r"(?:"
r"НЭГДҮГЭЭР|ХОЁРДУГААР|ГУРАВДУГААР|ДӨРӨВДҮГЭЭР|ТАВДУГААР|ЗУРГАДУГААР|ДОЛДУГААР|НАЙМДУГААР|ЕСДҮГЭЭР|АРАВДУГААР|"
r"АРВАН\s*НЭГДҮГЭЭР|АРВАН\s*ХОЁРДУГААР|АРВАН\s*ГУРАВДУГААР|АРВАН\s*ДӨРӨВДҮГЭЭР|АРВАН\s*ТАВДУГААР|"
r"АРВАН\s*ЗУРГАДУГААР|АРВАН\s*ДОЛДУГААР|АРВАН\s*НАЙМДУГААР|АРВАН\s*ЕСДҮГЭЭР|"
r"ХОРЬДУГААР|ХОРИН\s*НЭГДҮГЭЭР|ХОРИН\s*ХОЁРДУГААР|ХОРИН\s*ГУРАВДУГААР|ХОРИН\s*ДӨРӨВДҮГЭЭР|"
r"ХОРИН\s*ТАВДУГААР|ХОРИН\s*ЗУРГАДУГААР|ХОРИН\s*ДОЛДУГААР|ХОРИН\s*НАЙМДУГААР|ХОРИН\s*ЕСДҮГЭЭР|"
r"ГУЧДУГААР"
r")"
)
chapter_header_re = re.compile(
rf"^\s*({chapter_ordinal})\s+БҮЛЭГ\b.*$", re.IGNORECASE | re.MULTILINE
)
def normalize_header(h: str) -> str:
"""Make a neat filename fragment: collapse multiple spaces and uppercase."""
cleaned = re.sub(r"\s+", " ", h.strip())
return cleaned.upper().replace(" ", "_")
def main():
# Ensure output directory exists
Path(OUTPUT_DIR).mkdir(parents=True, exist_ok=True)
# Read the whole input file (UTF-8)
with open(INPUT_FILE, "r", encoding="utf-8") as f:
text = f.read()
# Find all chapter headers with their positions
matches = list(chapter_header_re.finditer(text))
if not matches:
raise SystemExit("No chapter headers found. Check the input file or regex.")
# Slice text into chapters
chapters = []
for i, m in enumerate(matches):
start = m.start()
end = matches[i + 1].start() if i + 1 < len(matches) else len(text)
chapter_text = text[start:end].rstrip()
header_text = m.group(0) # full header line
ordinal_text = m.group(1) # the ordinal portion for filename
chapters.append((header_text, ordinal_text, chapter_text))
# Write chapter files as 01..30 with header in filename
for idx, (header, ordinal, body) in enumerate(chapters, start=1):
num = f"{idx:02d}"
fname = f"{num}_{normalize_header(ordinal)}_БҮЛЭГ.txt"
out_path = os.path.join(OUTPUT_DIR, fname)
with open(out_path, "w", encoding="utf-8") as out:
out.write(body if body.endswith("\n") else body + "\n")
print(f"Wrote: {out_path}")
# Optional sanity check for 30 chapters
if len(chapters) != 30:
print(f"Warning: Expected 30 chapters, found {len(chapters)}. "
f"Check headings or regex.")
if __name__ == "__main__":
main()