Datasets:
Tasks:
Text Classification
Formats:
parquet
Languages:
Ancient Greek (to 1453)
Size:
100K - 1M
ArXiv:
License:
Download scripts/model_facing.py from Urdatorn/sphragis: direct link, hf CLI and curl.
- Browser
- Download file 15.8 kB
-
https://huggingface.co/datasets/Urdatorn/sphragis/resolve/main/scripts/model_facing.py
- Command line
-
hf download hf://datasets/Urdatorn/sphragis/scripts/model_facing.py
-
curl -L -o model_facing.py https://huggingface.co/datasets/Urdatorn/sphragis/resolve/main/scripts/model_facing.py
15.8 kB
| """Produce the scheme-neutral, identifier-free CoNLL-U that models are given. | |
| Sphragis draws on seven annotation projects whose author inventories do not | |
| overlap. Every convention that separates those projects therefore separates | |
| authors as well, and a model can score highly by recognizing the annotator | |
| instead of the writer. This module reduces every published tree to one shared | |
| representation and lifts the project-specific material into a separate audit | |
| column. | |
| The transformation, in order: | |
| * editorial punctuation tokens are removed and the tree is re-indexed, because | |
| UD PROIEL does not tokenize punctuation at all and its absence alone | |
| identifies its single author; | |
| * word forms and lemmas are lowercased with ``grc_utils.lower_grc``, because | |
| capitalization marks sentence openings and proper nouns inconsistently | |
| across projects and editions; | |
| * XPOS, UPOS, FEATS and DEPREL are collapsed onto the shared inventories in | |
| :mod:`syntax_normalization`; | |
| * MISC is cleared, because ``NativeRel``/``NativeHead``/``HeadRepair`` mark the | |
| natively converted projects on every token and ``SpaceAfter`` marks UD | |
| Perseus alone; | |
| * the ``# text`` comment is dropped, because the ``text`` column already | |
| carries it. | |
| Everything removed from MISC is returned as a compact ``native_syntax`` | |
| record so the original annotation stays auditable and remappable. | |
| """ | |
| from __future__ import annotations | |
| import re | |
| import unicodedata | |
| from grc_utils import lower_grc, vowel | |
| try: | |
| from scripts.syntax_normalization import ( | |
| CORE_XPOS_POS, | |
| CORE_XPOS_TO_UPOS, | |
| canonical_feats, | |
| core_deprel, | |
| core_feats, | |
| core_upos, | |
| core_xpos, | |
| is_editorial_punctuation, | |
| normalize_cc_heads, | |
| punctuationless_tokens, | |
| ) | |
| except ModuleNotFoundError: # Direct execution from the scripts directory. | |
| from syntax_normalization import ( | |
| CORE_XPOS_POS, | |
| CORE_XPOS_TO_UPOS, | |
| canonical_feats, | |
| core_deprel, | |
| core_feats, | |
| core_upos, | |
| core_xpos, | |
| is_editorial_punctuation, | |
| normalize_cc_heads, | |
| punctuationless_tokens, | |
| ) | |
| TOKEN_ID = re.compile(r"\d+") | |
| TOKEN_FIELDS = frozenset( | |
| ("id", "form", "lemma", "upos", "feats", "head", "deprel") | |
| ) | |
| AUDIT_MISC_KEYS = ("NativeRel", "NativeHead", "HeadRepair", "HeadConverted") | |
| # Elision is written differently by every project, and the difference alone | |
| # identifies the source. AGDT and UD Perseus mark it with a trailing combining | |
| # comma (δ̓, ἀλλ̓); Gorman uses three different apostrophe characters in the same | |
| # corpus (᾽, ʼ, ’); Pedalion and PROIEL use ’. Stripping the mark leaves the | |
| # same truncated word form everywhere, which is the only scheme-neutral choice. | |
| SMOOTH_BREATHING = "\u0313" | |
| ROUGH_BREATHING = "\u0314" | |
| KORONIS = "\u0343" | |
| ELISION_MARKS = frozenset((SMOOTH_BREATHING, ROUGH_BREATHING, KORONIS)) | |
| RHO = "\u03c1" | |
| def strip_elision(value: str) -> str: | |
| """Remove a word-final elision mark written as a combining breathing. | |
| A breathing on a vowel is ordinary orthography (ὁ, οὐ, εἰ), so only a | |
| trailing mark whose base letter is a consonant can be an elision. Rho is | |
| the one consonant that carries a breathing in its own right: the rough | |
| breathing of ῥ is kept, while a smooth breathing on rho is the elision | |
| convention (ἄῤ for ἄρα). Elided ῥα appears as ῥ̓ in some sources and as ῤ̓ | |
| in others, so marks are removed to a fixed point rather than one at a | |
| time: ῥ̓ keeps the rough breathing rho is entitled to, while ῤ̓ loses both. | |
| Reaching a fixed point is what makes this idempotent, which | |
| check_model_facing_conllu relies on to verify every published form. | |
| """ | |
| decomposed = unicodedata.normalize("NFD", value) | |
| while len(decomposed) > 1 and decomposed[-1] in ELISION_MARKS: | |
| base = next( | |
| ( | |
| character for character in reversed(decomposed[:-1]) | |
| if not unicodedata.combining(character) | |
| ), | |
| None, | |
| ) | |
| elided = base is not None and not vowel(base) and not ( | |
| base == RHO and decomposed[-1] == ROUGH_BREATHING | |
| ) | |
| if not elided: | |
| break | |
| decomposed = decomposed[:-1] | |
| return unicodedata.normalize("NFC", decomposed) | |
| def normalize_form(value: str) -> str: | |
| """Return a word form or lemma in the shared orthography. | |
| Order matters. Bracketed and hyphenated forms go first, so that an elision | |
| mark inside them ([τ̓]) is word-final by the time it is looked for, and NFC | |
| goes last, because lowercasing a capital that has no precomposed polytonic | |
| form (Ρ̓ῶμε) leaves a decomposed string that would not compare equal to its | |
| own normalization. | |
| """ | |
| if not value or value == "_": | |
| # A source project that gives no lemma writes "" or "_"; both are | |
| # published as the CoNLL-U placeholder. | |
| return "_" | |
| cleaned = "".join(punctuationless_tokens(value)) | |
| if not cleaned: | |
| # Only a lemma can get here (forms without a Greek letter are dropped | |
| # as tokens); an all-apparatus lemma such as ?? or ... is unknown. | |
| return "_" | |
| return unicodedata.normalize("NFC", lower_greek(strip_elision(cleaned))) | |
| def lower_greek(value: str) -> str: | |
| """Lowercase Greek without disturbing ``_`` placeholders or markup. | |
| ``grc_utils.lower_grc`` handles the precomposed polytonic letters, which | |
| ``str.lower`` gets wrong; it does not cover a handful of bare capitals | |
| (Ι, Ρ, Ά) or the stray Latin letters a few source files contain, so those | |
| fall back to ``str.lower`` character by character. | |
| """ | |
| if not value or value == "_": | |
| return value | |
| return "".join( | |
| character if not character.isupper() else character.lower() | |
| for character in lower_grc(value) | |
| ) | |
| GREEK_LETTER = re.compile(r"[\u0370-\u03ff\u1f00-\u1fff]") | |
| def is_word_token(form: str) -> bool: | |
| """A published token must contain a Greek letter. | |
| A letter, not merely a code point of the Greek blocks: the spacing | |
| breathings and accents (῾, ᾿, ´) live in the same block and are symbols. | |
| Everything else is editorial apparatus that survived upstream tokenisation: | |
| Pedalion's ``g`` gap markers, fragment numbers, backtick quotation marks, | |
| which Unicode files as a modifier symbol rather than punctuation, and a | |
| combining elision mark that was tokenised on its own. None of it is the | |
| author's Greek, and every one of them identifies a source file. | |
| """ | |
| # The archaic numeral letters (stigma, digamma, koppa, sampi) count as | |
| # letters here; a sentence that contains one is excluded as unrepresentable | |
| # by tracks.remove_unrepresentable_rows, and the span and crop reductions | |
| # (tracks.normalize, syntax_text_normalize) give them no extent. | |
| return any( | |
| GREEK_LETTER.match(character) and unicodedata.category(character).startswith("L") | |
| for character in unicodedata.normalize("NFC", form) | |
| ) | |
| def is_punctuation_token(form: str) -> bool: | |
| """Decide from the form alone whether a token is editorial punctuation. | |
| The tag is deliberately not consulted. Some upstream trees have their tag | |
| column offset against their forms, so that real words carry ``PUNCT`` and | |
| the commas beside them carry word tags; trusting the tag there deletes the | |
| words and keeps the commas. A form without a Greek letter is punctuation or | |
| apparatus whatever it was tagged. | |
| """ | |
| return not is_word_token(form) | |
| def punctuationless_text(text: str) -> str: | |
| """Return a text unit in the same orthography as its CoNLL-U forms.""" | |
| cleaned = "".join( | |
| " " if is_editorial_punctuation(character) else character | |
| for character in text | |
| ) | |
| return " ".join( | |
| strip_elision(word) for word in cleaned.split() if is_word_token(word) | |
| ) | |
| def _rows(conllu: str) -> list[list[str]]: | |
| rows = [] | |
| for line in conllu.splitlines(): | |
| if not line or line.startswith("#"): | |
| continue | |
| columns = line.split("\t") | |
| if len(columns) != 10: | |
| raise ValueError(f"CoNLL-U line does not have ten columns: {line!r}") | |
| if not TOKEN_ID.fullmatch(columns[0]): | |
| raise ValueError( | |
| f"published CoNLL-U must contain only integer token rows: {columns[0]!r}" | |
| ) | |
| rows.append(columns) | |
| if not rows: | |
| raise ValueError("cannot finalize an empty CoNLL-U document") | |
| return rows | |
| def _native_record(index: int, source_id: int, misc: str) -> dict | None: | |
| """Lift one token's source annotation out of MISC. | |
| ``token`` indexes the published token; ``source_token`` and ``head`` are | |
| the source document's own numbering, which ``NativeHead`` refers to. | |
| """ | |
| if not misc or misc == "_": | |
| return None | |
| values = {} | |
| for item in misc.split("|"): | |
| key, _, value = item.partition("=") | |
| if key in AUDIT_MISC_KEYS: | |
| values[key] = value | |
| if not values: | |
| return None | |
| return { | |
| "token": index, | |
| "source_token": source_id, | |
| "relation": values.get("NativeRel"), | |
| "head": values.get("NativeHead"), | |
| "head_repair": values.get("HeadRepair") == "Yes", | |
| # The Prague-style native head was rewritten to the UD convention. | |
| "head_converted": values.get("HeadConverted") == "Yes", | |
| } | |
| def finalize_conllu(conllu: str) -> tuple[list[dict], list[dict]]: | |
| """Return one sentence as published tokens, plus its audit records. | |
| Punctuation tokens are dropped and every dependent that hung from one is | |
| re-attached to that token's nearest surviving ancestor, so the result is | |
| still a single connected tree. | |
| """ | |
| rows = _rows(conllu) | |
| by_id = {int(row[0]): row for row in rows} | |
| dropped = {int(row[0]) for row in rows if is_punctuation_token(row[1])} | |
| kept = [row for row in rows if int(row[0]) not in dropped] | |
| if not kept: | |
| raise ValueError("removing punctuation left no tokens") | |
| kept_ids = {int(row[0]) for row in kept} | |
| def surviving_ancestor(token_id: int) -> int: | |
| head = int(by_id[token_id][6]) | |
| seen = {token_id} | |
| while head and head not in kept_ids: | |
| if head in seen or head not in by_id: | |
| return 0 | |
| seen.add(head) | |
| head = int(by_id[head][6]) | |
| return head | |
| resolved = {int(row[0]): surviving_ancestor(int(row[0])) for row in kept} | |
| # Coordinators hang on the conjunct that follows them in every project; | |
| # UD Perseus alone put them on the first conjunct, and that named it. | |
| kept_ids_in_order = [int(row[0]) for row in kept] | |
| resolved = dict(zip(kept_ids_in_order, normalize_cc_heads( | |
| kept_ids_in_order, | |
| [resolved[token_id] for token_id in kept_ids_in_order], | |
| [row[7] for row in kept], | |
| ))) | |
| roots = [token_id for token_id, head in resolved.items() if head == 0] | |
| primary_root = roots[0] if roots else int(kept[0][0]) | |
| id_map = {int(row[0]): new_id for new_id, row in enumerate(kept, 1)} | |
| native: list[dict] = [] | |
| output: list[dict] = [] | |
| for row in kept: | |
| old_id = int(row[0]) | |
| record = _native_record(id_map[old_id], old_id, row[9]) | |
| if record is not None: | |
| native.append(record) | |
| head = resolved[old_id] | |
| if old_id == primary_root: | |
| new_head, relation = 0, "root" | |
| else: | |
| # A source tree with more than one root, or one whose root was the | |
| # punctuation token just removed, still has to publish exactly one. | |
| new_head = id_map[head] if head else id_map[primary_root] | |
| relation = core_deprel(row[7]) | |
| if relation in {"root", "punct"}: | |
| relation = "dep" | |
| xpos = core_xpos(row[4]) | |
| if xpos[0] == "u": | |
| # A surviving token tagged as punctuation comes from a tree whose | |
| # tag column is offset; its real part of speech is unknown. | |
| xpos = "x" + xpos[1:] | |
| # XPOS is folded into FEATS here and not published: the two carried | |
| # different distinctions and had already drifted apart. | |
| feats = canonical_feats(xpos, row[5]) | |
| output.append({ | |
| "id": id_map[old_id], | |
| "form": normalize_form(row[1]), | |
| "lemma": normalize_form(row[2]), | |
| "upos": core_upos(xpos), | |
| "feats": None if feats == "_" else feats, | |
| "head": new_head, | |
| "deprel": relation, | |
| }) | |
| return output, native | |
| def source_conllu_blocks(unit: str) -> list[str]: | |
| """Split a source CoNLL-U unit into its sentence blocks.""" | |
| return [block for block in unit.split("\n\n") if block.strip()] | |
| def finalize_conllu_unit(unit: str) -> tuple[list[list[dict]], list[dict]]: | |
| """Finalize every sentence in one source CoNLL-U unit. | |
| A Sphragis Metre line can span a sentence boundary, in which case its unit | |
| holds two or more blocks, each numbered from 1. They must be finalized | |
| separately: merging them would collide their token ids, point heads across | |
| a sentence boundary and leave the unit with more than one root. Every audit | |
| record carries ``sentence``, so that ``token`` stays unambiguous. | |
| """ | |
| blocks = source_conllu_blocks(unit) | |
| if not blocks: | |
| raise ValueError("cannot finalize an empty CoNLL-U unit") | |
| sentences = [] | |
| native: list[dict] = [] | |
| for index, block in enumerate(blocks): | |
| tokens, block_native = finalize_conllu(block) | |
| sentences.append(tokens) | |
| native.extend({**record, "sentence": index} for record in block_native) | |
| return sentences, native | |
| CORE_UPOS = frozenset(CORE_XPOS_TO_UPOS.values()) - {"PUNCT"} | |
| def check_model_facing_conllu(unit: list[list[dict]], where: str) -> None: | |
| """Assert every invariant the model-facing representation guarantees. | |
| Each of these removes a channel through which the annotating project, and | |
| therefore the author, could be recognized without reading the Greek. | |
| """ | |
| assert unit, f"{where}: CoNLL-U unit contains no sentence" | |
| for index, sentence in enumerate(unit): | |
| _check_sentence(sentence, f"{where}, sentence {index}") | |
| def _check_sentence(sentence: list[dict], where: str) -> None: | |
| assert sentence, f"{where}: sentence contains no token" | |
| ids = [token["id"] for token in sentence] | |
| assert ids == list(range(1, len(ids) + 1)), f"{where}: token ids are not contiguous" | |
| heads = [token["head"] for token in sentence] | |
| assert heads.count(0) == 1, f"{where}: expected exactly one root, got {heads.count(0)}" | |
| for token in sentence: | |
| assert set(token) == TOKEN_FIELDS, f"{where}: unexpected token fields {set(token)}" | |
| assert token["head"] in range(0, len(ids) + 1), ( | |
| f"{where}: head {token['head']} is outside the sentence" | |
| ) | |
| upos, deprel = token["upos"], token["deprel"] | |
| assert upos in CORE_UPOS, f"{where}: UPOS {upos!r} is outside the shared inventory" | |
| assert upos != "PUNCT", f"{where}: punctuation tokens are not published" | |
| assert core_deprel(deprel) == deprel and deprel != "punct", ( | |
| f"{where}: DEPREL {deprel!r} is outside the shared inventory" | |
| ) | |
| feats = token["feats"] | |
| assert feats is None or (feats != "_" and core_feats(feats) == feats), ( | |
| f"{where}: FEATS {feats!r} is outside the shared inventory" | |
| ) | |
| for name in ("form", "lemma"): | |
| value = token[name] | |
| if value == "_": | |
| continue | |
| assert value == normalize_form(value), ( | |
| f"{where}: {name} {value!r} is not in the shared orthography" | |
| ) | |