File size: 13,898 Bytes
83dae89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
667319c
 
 
 
 
 
 
 
 
 
83dae89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
531a22f
 
 
 
 
 
 
83dae89
 
531a22f
83dae89
531a22f
 
83dae89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6fc8784
 
1e6d8b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6fc8784
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13ef6e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
265998e
 
 
 
 
6fc8784
 
 
 
 
 
 
 
 
 
 
 
265998e
 
 
6fc8784
265998e
 
 
 
 
 
6fc8784
265998e
6fc8784
 
265998e
 
 
 
 
6fc8784
 
 
 
 
 
 
 
 
 
 
 
 
13ef6e2
6fc8784
 
 
 
265998e
6fc8784
 
 
 
13ef6e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
265998e
13ef6e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6fc8784
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Uniform preprocessing and UD-v2 normalization for automatic syntax."""

from __future__ import annotations

import unicodedata


UNIVERSAL_DEPRELS = frozenset({
    "acl", "advcl", "advmod", "amod", "appos", "aux", "case", "cc",
    "ccomp", "clf", "compound", "conj", "cop", "csubj", "dep", "det",
    "discourse", "dislocated", "expl", "fixed", "flat", "goeswith", "iobj",
    "list", "mark", "nmod", "nsubj", "nummod", "obj", "obl", "orphan",
    "parataxis", "punct", "reparandum", "root", "vocative", "xcomp",
})

# Hypotactic also uses these apostrophe/koronis characters as token-attached
# marks. Unicode does not classify all of them as punctuation.
PUNCTUATION_LIKE = frozenset({"ʼ", "᾽", "᾿", "῾"})


def is_editorial_punctuation(character: str) -> bool:
    """Punctuation, symbols and digits are apparatus, never the author's Greek.

    Symbols (category S) cover the angle brackets of editorial supplements
    (<ἄλαστ>), the tilde and acute some files use for a circumflex or accent
    (δι~ος, ει´κω) and the spacing breathings (῎, ῞) written before a capital.
    Digits (category N) are Morpheus sense indices on lemmas (λέγω3), which
    only some projects write, and stray line numbers glued to a form
    (ἔλλαχες1). Each of them survives in the files of a few authors only.
    """
    return unicodedata.category(character)[0] in "PSN" or character in PUNCTUATION_LIKE


def punctuationless_tokens(token: str) -> list[str]:
    """Remove punctuation, treating it as a boundary rather than joining words."""
    cleaned = "".join(
        " " if is_editorial_punctuation(character) else character
        for character in token
    )
    return [
        piece for piece in cleaned.split()
        if any(character.isalpha() for character in piece)
    ]


def punctuationless_lemma(lemma: str) -> str:
    """Remove any punctuation a tagger retained or generated inside a lemma."""
    return "".join(punctuationless_tokens(lemma)) or "_"


def syntax_text_normalize(value: str) -> str:
    """Normalize letters for punctuationless parser span and coverage checks.

    The same reduction as ``tracks.normalize``: lowercased Greek letters with
    final sigma folded and no diacritics, without the archaic numeral letters
    (stigma, digamma, koppa, sampi), which the parser's tokeniser drops. Every
    span, crop and coverage check must measure text the same way.
    """
    return "".join(
        character
        for character in unicodedata.normalize("NFD", value.lower().replace("ς", "σ"))
        if unicodedata.category(character) != "Mn"
        and "\u0370" <= character <= "\u03ff" and character.isalpha()
        and not ("\u03da" <= character <= "\u03e1")
    )


def canonical_stoicheia_deprel(relation: str | None, upos: str, head: int) -> str:
    """Return a UD-v2 relation, repairing Stoicheia's residual AGDT labels."""
    if head == 0:
        return "root"
    raw = (relation or "dep").strip()
    base, separator, subtype = raw.partition(":")
    lower_base = base.lower()
    if lower_base in UNIVERSAL_DEPRELS:
        return lower_base + (f":{subtype.lower()}" if separator and subtype else "")

    legacy = {
        "auxp": "case",
        "auxc": "cc" if upos == "CCONJ" else "mark",
        "auxv": "aux",
        "auxy": "discourse",
        "auxz": "advmod",
    }
    return legacy.get(lower_base, "dep")


def is_universal_deprel(relation: str) -> bool:
    return relation.split(":", 1)[0] in UNIVERSAL_DEPRELS


def normalize_cc_heads(ids: list[int], heads: list[int], deprels: list[str]) -> list[int]:
    """Attach every coordinator to the conjunct that follows it.

    The projects disagree about where ``cc`` hangs: PROIEL puts it on the
    conjunct after the conjunction, as the UD guidelines say, UD Perseus on
    the first conjunct, and a parser trained on both does either. Since the
    projects' author inventories do not overlap, the difference named the
    author. Every layer and every project is reduced to the guideline here.
    A coordinator with no conjunct after it (καί opening a sentence, a
    postposed τε) stays on the last member, which is the coordination head
    itself when there is no ``conj`` at all.
    """
    position = {token_id: index for index, token_id in enumerate(ids)}
    base = [deprel.split(":", 1)[0] if deprel else "" for deprel in deprels]
    conjuncts: dict[int, list[int]] = {}
    for token_id, head, relation in zip(ids, heads, base):
        if relation == "conj" and head in position:
            conjuncts.setdefault(head, []).append(token_id)
    output = list(heads)
    for index, (token_id, head, relation) in enumerate(zip(ids, heads, base)):
        if relation != "cc" or head not in position:
            continue
        governor = head
        if base[position[head]] == "conj" and heads[position[head]] in position:
            governor = heads[position[head]]
        members = [governor, *sorted(conjuncts.get(governor, []))]
        following = [member for member in members if member > token_id]
        output[index] = following[0] if following else members[-1]
    return output


# ---------------------------------------------------------------------------
# Scheme-neutral model-facing normalization.
#
# Sphragis merges seven annotation projects whose author inventories do not
# overlap, so any convention that distinguishes those projects also identifies
# the author. The mappings below reduce every source to one shared inventory,
# so that a category boundary the projects disagree about cannot be used as an
# authorship feature. See metadata/leakage_report.json for the measured effect.
# ---------------------------------------------------------------------------

# AGDT nine-position part of speech (XPOS position 1) after normalization.
# ``l``/``p`` (article, pronoun) and ``d``/``g``/``c``/``b`` (adverb, particle,
# conjunction) are merged because the projects disagree about exactly these
# boundaries for the highest-frequency Greek function words: δέ is a particle
# in AGDT, an adverb in Gorman and a coordinator in UD Perseus; καί is a
# subordinator in the AGDT lineage and a coordinator in UD.
CORE_XPOS_POS = {
    "n": "n", "v": "v", "t": "v", "a": "a",
    "p": "p", "l": "p",
    "d": "d", "g": "d", "c": "d", "b": "d",
    "r": "r", "m": "m", "i": "i",
    "u": "u",
    "x": "x", "e": "x", "z": "x", "-": "x",
}

CORE_XPOS_TO_UPOS = {
    "n": "NOUN", "v": "VERB", "a": "ADJ", "p": "PRON", "d": "ADV",
    "r": "ADP", "m": "NUM", "i": "INTJ", "u": "PUNCT", "x": "X",
}

# Morphological features published for every token. ``PronType``,
# ``Definite``, ``Polarity``, ``Poss`` and ``Reflex`` are excluded because they
# occur in one project only. ``Aspect`` and ``VerbForm`` are included but never
# taken from a source project, for the same reason: the build derives them
# from the normalized XPOS, uniformly, in canonical_feats below.
CORE_FEATS = (
    "Aspect", "Case", "Degree", "Gender", "Mood", "Number", "Person",
    "Tense", "VerbForm", "Voice",
)

# The nine-position tag distinguishes all seven Greek tenses, which UD's
# ``Tense`` alone cannot: aorist, imperfect, perfect and pluperfect all read as
# ``Tense=Past``. Pairing Tense with Aspect keeps them apart in standard UD
# values, so the positional tag itself need not be published.
XPOS_TENSE = {
    "p": (("Tense", "Pres"), ("Aspect", "Imp")),    # present
    "i": (("Tense", "Past"), ("Aspect", "Imp")),    # imperfect
    "a": (("Tense", "Past"), ("Aspect", "Perf")),   # aorist
    "r": (("Tense", "Pres"), ("Aspect", "Perf")),   # perfect
    "l": (("Tense", "Pqp"), ("Aspect", "Perf")),    # pluperfect
    "f": (("Tense", "Fut"),),                        # future
    "t": (("Tense", "Fut"), ("Aspect", "Perf")),    # future perfect
}

# ``n``, ``p`` and ``g`` are not moods. They were the only record that a verb
# was non-finite, and FEATS lost it: 20,798 infinitives and participles carried
# no VerbForm at all, while others carried a non-standard ``Mood=Inf``.
XPOS_MOOD = {
    "i": (("Mood", "Ind"), ("VerbForm", "Fin")),
    "s": (("Mood", "Sub"), ("VerbForm", "Fin")),
    "o": (("Mood", "Opt"), ("VerbForm", "Fin")),
    "m": (("Mood", "Imp"), ("VerbForm", "Fin")),
    "n": (("VerbForm", "Inf"),),
    "p": (("VerbForm", "Part"),),
    "g": (("VerbForm", "Ger"),),
}

# ``e`` is the medio-passive, whose form does not decide between middle and
# passive; FEATS flattened it onto ``Mid`` alongside the true middle ``m``.
XPOS_VOICE = {
    "a": "Act", "p": "Pass", "m": "Mid", "e": "Mid,Pass",
}

# ``c`` is the common gender, which only some projects tag. It varied
# twenty-six times more between annotators than between authors, so it is not
# published: those tokens simply carry no Gender.
XPOS_GENDER = {"m": "Masc", "f": "Fem", "n": "Neut"}
UNPUBLISHED_FEATS = frozenset({"Gender=Com"})

# Shared dependency inventory. Relations are merged wherever the projects
# express one analysis with different labels: ``det`` joins the attributive
# bucket because the AGDT lineage annotates the article as an attribute, and
# ``cc``/``cop``/``aux`` join the functional bucket because native schemes
# never produce them.
CORE_DEPREL = {
    "root": "root",
    "nsubj": "nsubj", "csubj": "nsubj",
    "obj": "obj", "iobj": "obj",
    "ccomp": "ccomp", "xcomp": "ccomp",
    "obl": "obl",
    # ``appos`` is merged away: whether a nominal is an apposition or an
    # ordinary modifier is an analytic preference, and it varied twelve times
    # more between two annotators of one author than between authors.
    "nmod": "nmod", "amod": "nmod", "nummod": "nmod", "det": "nmod",
    "appos": "nmod",
    # The Greek particles are the same tokens everywhere; UD Perseus files them
    # as adverbs and the AGDT lineage as discourse markers, at rates differing
    # forty-fold while their sum agrees. Merging the two costs a distinction
    # the projects do not share, and which UPOS already stopped drawing when
    # PART, CCONJ, SCONJ and ADV were merged.
    "advmod": "advmod", "acl": "advmod", "advcl": "advmod",
    "discourse": "advmod", "dislocated": "advmod",
    "case": "case", "mark": "case", "cc": "case", "cop": "case", "aux": "case",
    "conj": "conj",
    # ``vocative`` carried no authorial signal at all — it did not vary between
    # sixteen authors of one project — while varying between annotators of one
    # author. FEATS ``Case=Voc`` identifies vocatives exactly, so the relation
    # was redundant as well as leaky.
    "vocative": "dep",
    "punct": "punct",
}

CORE_DEPRELS = frozenset(CORE_DEPREL.values()) | {"dep"}


def core_deprel(relation: str) -> str:
    """Collapse a relation onto the inventory every source project shares."""
    base = (relation or "dep").split(":", 1)[0].lower()
    return CORE_DEPREL.get(base, "dep")


def core_feats(feats: str) -> str:
    """Retain only the morphological features in the shared inventory."""
    if not feats or feats == "_":
        return "_"
    retained = [
        item for item in feats.split("|")
        if item.split("=", 1)[0] in CORE_FEATS and item not in UNPUBLISHED_FEATS
    ]
    return "|".join(sorted(retained)) or "_"


def canonical_feats(xpos: str, feats: str) -> str:
    """Return the one published morphological analysis of a token.

    XPOS and FEATS each carried distinctions the other lost, and disagreed
    with each other: the positional tag alone separated the Greek tenses and
    the medio-passive, while FEATS alone recorded ambiguous genders such as
    ``Masc,Neut``. Publishing both invited them to drift further apart, so the
    positional tag is folded in here and then dropped.

    Tense, Aspect, Mood, VerbForm and Voice are taken from the normalized
    XPOS, which makes them uniform across source projects rather than
    inherited from whichever project annotated the sentence. Gender and the
    remaining features keep their FEATS values, which are the finer of the two.
    """
    parsed = dict(
        item.split("=", 1) for item in feats.split("|")
        if feats and feats != "_" and "=" in item
    )
    derived = {
        key: value for key in ("Case", "Degree", "Gender", "Number", "Person")
        if (value := parsed.get(key)) is not None
        and f"{key}={value}" not in UNPUBLISHED_FEATS
    }
    if not xpos or xpos == "_":
        return core_feats("|".join(f"{k}={v}" for k, v in sorted(derived.items())))

    for slot, table in ((3, XPOS_TENSE), (4, XPOS_MOOD)):
        for key, value in table.get(xpos[slot], ()):
            derived[key] = value
    voice = XPOS_VOICE.get(xpos[5])
    if voice is not None:
        derived["Voice"] = voice
    if "Gender" not in derived and xpos[6] in XPOS_GENDER:
        derived["Gender"] = XPOS_GENDER[xpos[6]]
    # A tag whose slot was blank still keeps whatever FEATS recorded, so the
    # pluperfects and participles the tag missed are not lost either.
    for key in ("Tense", "Mood", "Voice"):
        if key not in derived and key in parsed and parsed[key] not in {"Inf", "Part"}:
            derived[key] = parsed[key]
    if parsed.get("Mood") in {"Inf", "Part"} and "VerbForm" not in derived:
        derived["VerbForm"] = parsed["Mood"]
    return "|".join(f"{key}={derived[key]}" for key in sorted(derived)) or "_"


def core_xpos(xpos: str) -> str:
    """Merge the part-of-speech position onto the shared inventory."""
    if not xpos or xpos == "_":
        return xpos
    if len(xpos) != 9:
        raise ValueError(f"XPOS must have exactly nine positions, got {xpos!r}")
    return CORE_XPOS_POS.get(xpos[0], "x") + xpos[1:]


def core_upos(xpos: str) -> str:
    """Derive UPOS from the normalized XPOS so both columns share one scheme."""
    if not xpos or xpos == "_":
        return "X"
    return CORE_XPOS_TO_UPOS.get(CORE_XPOS_POS.get(xpos[0], "x"), "X")