File size: 4,946 Bytes
bc3f388
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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),
            )