yacht's picture
OpenThai2.0-NLP-Core-Benchmark 1.1: test sets, scorers and system outputs for six Thai tasks.
0e6d825
Raw History Blame Contribute Delete
4.88 kB
"""Minimal CoNLL-U reading and writing for single-word tokens (Thai treebanks have no ranges).
A sentence keeps its comment lines, so a file written back is the same file. Words carry their
character span in the sentence text, which the raw-text scorer and the models need.
"""
from __future__ import annotations
from dataclasses import dataclass, field
from pathlib import Path
@dataclass
class Word:
"""One CoNLL-U word line (columns 1-10) plus its span in the sentence text."""
form: str
upos: str = "_"
head: int = -1 # -1 = unknown (no tree), 0 = root
deprel: str = "_"
xpos: str = "_"
feats: str = "_"
misc: str = "_"
start: int = -1
end: int = -1
@property
def space_after(self) -> bool:
return "SpaceAfter=No" not in self.misc.split("|")
@dataclass
class Sentence:
words: list[Word]
comments: list[str] = field(default_factory=list)
@property
def text(self) -> str:
"""The `# text` comment, or the text rebuilt from forms and SpaceAfter."""
for c in self.comments:
if c.startswith("# text = "):
return c[len("# text = "):]
return rebuild_text(self.words)
@property
def sent_id(self) -> str:
for c in self.comments:
if c.startswith("# sent_id = "):
return c[len("# sent_id = "):]
return ""
def rebuild_text(words: list[Word]) -> str:
return "".join(w.form + (" " if w.space_after else "") for w in words).rstrip(" ")
def _set_spans(sent: Sentence) -> None:
"""Locate each word in the sentence text (left to right, skipping whitespace)."""
text = sent.text
pos = 0
for w in sent.words:
i = text.find(w.form, pos)
if i < 0 or text[pos:i].strip():
raise ValueError(f"word {w.form!r} not found at {pos} in {sent.sent_id}: {text!r}")
w.start, w.end = i, i + len(w.form)
pos = w.end
def read_conllu(path: str | Path, other_languages: bool = False) -> list[Sentence]:
"""Read a CoNLL-U file. Thai UD has no multiword ranges or empty nodes, so they are rejected, unless
`other_languages`: then empty nodes are skipped, a range's SpaceAfter moves to its last word, and words
get no character spans (their forms need not be substrings of the text)."""
sents: list[Sentence] = []
words: list[Word] = []
comments: list[str] = []
range_end, range_misc = -1, "_"
with open(path, encoding="utf-8") as f:
for line in f:
line = line.rstrip("\n")
if not line.strip():
if words:
sents.append(Sentence(words, comments))
words, comments = [], []
continue
if line.startswith("#"):
comments.append(line)
continue
c = line.split("\t")
if len(c) != 10:
raise ValueError(f"{path}: not 10 columns: {line!r}")
if "-" in c[0] or "." in c[0]:
if not other_languages:
raise ValueError(f"{path}: ranges/empty nodes not supported: {line!r}")
if "-" in c[0]:
range_end, range_misc = int(c[0].split("-")[1]), c[9]
continue
if int(c[0]) != len(words) + 1:
raise ValueError(f"{path}: id {c[0]} out of order")
head = int(c[6]) if c[6] not in ("_", "") else -1
misc = c[9]
if other_languages and int(c[0]) == range_end:
misc = range_misc # the token's SpaceAfter belongs to its last word
words.append(Word(form=c[1], upos=c[3], head=head, deprel=c[7], xpos=c[4], feats=c[5], misc=misc))
if words:
sents.append(Sentence(words, comments))
if not other_languages:
for s in sents:
_set_spans(s)
return sents
def format_sentence(sent: Sentence) -> str:
lines = list(sent.comments)
for i, w in enumerate(sent.words, 1):
head = "_" if w.head < 0 else str(w.head)
lines.append("\t".join([str(i), w.form, "_", w.upos, w.xpos, w.feats, head, w.deprel, "_", w.misc]))
return "\n".join(lines) + "\n\n"
def write_conllu(path: str | Path, sents: list[Sentence]) -> None:
with open(path, "w", encoding="utf-8") as f:
for s in sents:
f.write(format_sentence(s))
def words_from_spans(text: str, spans: list[tuple[int, int]]) -> list[Word]:
"""Words for a system output given as character spans of `text` (SpaceAfter from the text)."""
out = []
for k, (a, b) in enumerate(spans):
nxt = spans[k + 1][0] if k + 1 < len(spans) else len(text)
gap = text[b:nxt]
misc = "_" if (gap and gap[0].isspace()) or k + 1 == len(spans) else "SpaceAfter=No"
out.append(Word(form=text[a:b], misc=misc, start=a, end=b))
return out