"""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")