AjayRangoji's picture
Upload src
bc3f388 verified
Raw History Blame Contribute Delete
4.95 kB
"""Parse DCS CoNLL-U into verse records.
DCS stores each half-verse (pada pair) as its own sentence, grouped by
`# sent_counter`; Itihasa stores the whole verse on one line and its English
translates the whole verse. So we join DCS sentences sharing
(chapter_id, sent_counter) into one verse record (DECISIONS.md D16).
Gold split = the `Unsandhied=` values of the real token rows, in order.
Range rows (`1-3`) mark the sandhied surface token they expand to and carry no
annotation; they are skipped for the split but used to recover split locations.
"""
from __future__ import annotations
import os
import re
from dataclasses import dataclass, field
from typing import Iterator
from .normalize import normalize_iast
_MISC_RE = re.compile(r"(?:^|\|)Unsandhied=([^|]*)")
_RANGE_RE = re.compile(r"^\d+-\d+$")
@dataclass
class DcsSentence:
sent_id: str
chapter: str
chapter_id: str
sent_counter: str
text: str # sandhied, as DCS prints it
words: list[str] = field(default_factory=list) # unsandhied tokens
is_cpd: list[bool] = field(default_factory=list) # Case=Cpd -> compound-internal
@dataclass
class DcsVerse:
id: str
text_name: str
chapter: str
sent_ids: list[str]
sanskrit_raw: str # sandhied, normalised
sanskrit_gold: str # unsandhied words, space separated
n_cpd: int # compound-internal boundaries
n_words: int
def _misc_unsandhied(misc: str) -> str | None:
m = _MISC_RE.search(misc or "")
return m.group(1) if m else None
def parse_conllu_file(path: str) -> Iterator[DcsSentence]:
"""Yield DcsSentence objects from one DCS .conllu chapter file."""
chapter = chapter_id = ""
text = sent_id = sent_counter = ""
words: list[str] = []
is_cpd: list[bool] = []
have_sent = False
def flush():
nonlocal have_sent, words, is_cpd, text, sent_id, sent_counter
if have_sent and text:
yield_val = DcsSentence(
sent_id=sent_id, chapter=chapter, chapter_id=chapter_id,
sent_counter=sent_counter, text=text,
words=words, is_cpd=is_cpd,
)
words, is_cpd = [], []
have_sent = False
return yield_val
words, is_cpd = [], []
have_sent = False
return None
with open(path, encoding="utf-8") as fh:
for line in fh:
line = line.rstrip("\n")
if line.startswith("## chapter_id:"):
chapter_id = line.split(":", 1)[1].strip()
elif line.startswith("## chapter:"):
chapter = line.split(":", 1)[1].strip()
elif line.startswith("# text ="):
out = flush()
if out:
yield out
text = line.split("=", 1)[1].strip()
have_sent = True
elif line.startswith("# sent_id ="):
sent_id = line.split("=", 1)[1].strip()
elif line.startswith("# sent_counter ="):
sent_counter = line.split("=", 1)[1].strip()
elif line and not line.startswith("#"):
cols = line.split("\t")
if len(cols) < 10 or _RANGE_RE.match(cols[0]):
continue # range row: no annotation of its own
uns = _misc_unsandhied(cols[9]) or cols[1]
uns = normalize_iast(uns)
if uns:
words.append(uns)
is_cpd.append("Case=Cpd" in (cols[5] or ""))
out = flush()
if out:
yield out
def iter_verses(text_dir: str, text_name: str) -> Iterator[DcsVerse]:
"""Join half-verses sharing (chapter_id, sent_counter) into verse records."""
files = sorted(
(f for f in os.listdir(text_dir) if f.endswith(".conllu")),
key=lambda f: f,
)
for fname in files:
buf: dict[tuple[str, str], list[DcsSentence]] = {}
order: list[tuple[str, str]] = []
for s in parse_conllu_file(os.path.join(text_dir, fname)):
key = (s.chapter_id, s.sent_counter)
if key not in buf:
buf[key] = []
order.append(key)
buf[key].append(s)
for key in order:
sents = buf[key]
raw = normalize_iast(" ".join(s.text for s in sents))
words = [w for s in sents for w in s.words]
cpd = [c for s in sents for c in s.is_cpd]
if not raw or not words:
continue
yield DcsVerse(
id=f"dcs:{text_name}:{key[0]}:{key[1]}",
text_name=text_name,
chapter=sents[0].chapter,
sent_ids=[s.sent_id for s in sents],
sanskrit_raw=raw,
sanskrit_gold=" ".join(words),
n_cpd=sum(cpd),
n_words=len(words),
)