Datasets:
Tasks:
Text Classification
Formats:
parquet
Languages:
Ancient Greek (to 1453)
Size:
10K - 100K
License:
Add Stoicheia parsing for complete Hypotactic coverage
Browse files- .gitignore +2 -0
- CHANGELOG.md +2 -0
- README.md +2 -1
- requirements-stoicheia.txt +3 -0
- scripts/build_dataset.py +273 -8
- scripts/dataset_variants.py +15 -0
- scripts/stoicheia_parse_hypotactic.py +247 -0
- slurm/rebuild_dataset.slurm +4 -1
- slurm/stoicheia_parse_hypotactic.slurm +47 -0
- tests/test_split_stratification.py +29 -0
.gitignore
CHANGED
|
@@ -3,3 +3,5 @@ __pycache__/
|
|
| 3 |
.logs/
|
| 4 |
.build-stage-*/
|
| 5 |
.build-backup-*/
|
|
|
|
|
|
|
|
|
| 3 |
.logs/
|
| 4 |
.build-stage-*/
|
| 5 |
.build-backup-*/
|
| 6 |
+
.stoicheia-cache/
|
| 7 |
+
.hf-stoicheia/
|
CHANGELOG.md
CHANGED
|
@@ -10,6 +10,8 @@
|
|
| 10 |
Sphragis sentence publication and its metadata.
|
| 11 |
- Moved the scanned-line configurations to the separate `sphragis-metre`
|
| 12 |
dataset.
|
|
|
|
|
|
|
| 13 |
|
| 14 |
## 0.3.2-beta — 2026-08-18
|
| 15 |
|
|
|
|
| 10 |
Sphragis sentence publication and its metadata.
|
| 11 |
- Moved the scanned-line configurations to the separate `sphragis-metre`
|
| 12 |
dataset.
|
| 13 |
+
- Added a pinned, resumable Stoicheia parsing stage that supplies predicted
|
| 14 |
+
CoNLL-U for curated Hypotactic lines without gold syntax in `sphragis-metre`.
|
| 15 |
|
| 16 |
## 0.3.2-beta — 2026-08-18
|
| 17 |
|
README.md
CHANGED
|
@@ -224,7 +224,8 @@ Machine-readable reasons and pre-deduplication counts are recorded in
|
|
| 224 |
python -m pip install -r requirements-build.txt
|
| 225 |
python scripts/build_dataset.py --sources /path/to/frozen/checkouts \
|
| 226 |
--metre-output ../sphragis-metre/data \
|
| 227 |
-
--metre-metadata ../sphragis-metre/metadata
|
|
|
|
| 228 |
python scripts/validate_publication.py --publication sentence --data data
|
| 229 |
python scripts/validate_publication.py \
|
| 230 |
--publication metre --data ../sphragis-metre/data
|
|
|
|
| 224 |
python -m pip install -r requirements-build.txt
|
| 225 |
python scripts/build_dataset.py --sources /path/to/frozen/checkouts \
|
| 226 |
--metre-output ../sphragis-metre/data \
|
| 227 |
+
--metre-metadata ../sphragis-metre/metadata \
|
| 228 |
+
--stoicheia-conllu .stoicheia-cache/hypotactic_conllu.jsonl
|
| 229 |
python scripts/validate_publication.py --publication sentence --data data
|
| 230 |
python scripts/validate_publication.py \
|
| 231 |
--publication metre --data ../sphragis-metre/data
|
requirements-stoicheia.txt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
huggingface-hub>=0.34,<2
|
| 2 |
+
safetensors>=0.5,<1
|
| 3 |
+
transformers>=4.57,<5
|
scripts/build_dataset.py
CHANGED
|
@@ -161,6 +161,43 @@ VERSE_LINKS = {
|
|
| 161 |
}
|
| 162 |
|
| 163 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 164 |
PEDALION_VERSE = {
|
| 165 |
"achar.xml",
|
| 166 |
"thesmo.xml",
|
|
@@ -587,6 +624,8 @@ def authorship_decision(sentence: Sentence) -> tuple[str | None, str | None]:
|
|
| 587 |
author = f"Homeric-{work}"
|
| 588 |
|
| 589 |
lowered_author = author.casefold()
|
|
|
|
|
|
|
| 590 |
if lowered_author.startswith("unknown"):
|
| 591 |
return None, "unknown_author"
|
| 592 |
if lowered_author.startswith("anonymous"):
|
|
@@ -1039,7 +1078,8 @@ class HypotacticParser(HTMLParser):
|
|
| 1039 |
self.word_depth = None
|
| 1040 |
self.word_text = []
|
| 1041 |
if self.line_depth == self.depth and tag == "div":
|
| 1042 |
-
self.line["
|
|
|
|
| 1043 |
symbols = {"long": "–", "short": "⏑", "anceps": "×", "unknown": "?"}
|
| 1044 |
self.line["scansion"] = "".join(symbols[s["quantity"]] for s in self.line["syllables"])
|
| 1045 |
self.line["hypotactic_file"] = self.stem + ".html"
|
|
@@ -1050,6 +1090,7 @@ class HypotacticParser(HTMLParser):
|
|
| 1050 |
"poem_sequence": self.poem.get("sequence", "1"),
|
| 1051 |
})
|
| 1052 |
if self.line["text"] and self.line["number"]:
|
|
|
|
| 1053 |
self.lines.append(self.line)
|
| 1054 |
self.line = None
|
| 1055 |
self.line_depth = None
|
|
@@ -1063,7 +1104,10 @@ def parse_hypotactic_file(path: Path) -> list[dict]:
|
|
| 1063 |
parser = HypotacticParser(path.stem)
|
| 1064 |
parser.feed(path.read_text(encoding="utf8"))
|
| 1065 |
# Older files do not carry book metadata; recover it from their stem.
|
| 1066 |
-
book_match = re.match(
|
|
|
|
|
|
|
|
|
|
| 1067 |
for line in parser.lines:
|
| 1068 |
if not line["book"] and book_match:
|
| 1069 |
line["book"] = book_match.group(1)
|
|
@@ -1071,12 +1115,72 @@ def parse_hypotactic_file(path: Path) -> list[dict]:
|
|
| 1071 |
return parser.lines
|
| 1072 |
|
| 1073 |
|
| 1074 |
-
def load_hypotactic(root: Path) -> dict[str, list[dict]]:
|
| 1075 |
html_root = root / "hypotactic_htmls_greek"
|
| 1076 |
-
needed =
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1077 |
return {stem: parse_hypotactic_file(html_root / f"{stem}.html") for stem in needed}
|
| 1078 |
|
| 1079 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1080 |
def verse_sentence_order_key(sentence: Sentence) -> tuple:
|
| 1081 |
references = []
|
| 1082 |
for cite in sentence.native_cites:
|
|
@@ -1176,7 +1280,7 @@ def hypotactic_source_records(lines: list[dict], revisions: dict[str, str]) -> l
|
|
| 1176 |
source_record(
|
| 1177 |
"hypotactic", revisions, source_file,
|
| 1178 |
",".join(
|
| 1179 |
-
f"{line['poem_sequence']}:{line['book']}:{line['number']}"
|
| 1180 |
for line in file_lines
|
| 1181 |
),
|
| 1182 |
)
|
|
@@ -1367,6 +1471,152 @@ def align_verse_blocks(
|
|
| 1367 |
return sentence_rows, metre_rows, alignment_stats
|
| 1368 |
|
| 1369 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1370 |
def numeric_line_number(value: str) -> int | None:
|
| 1371 |
match = re.match(r"^(\d+)", str(value))
|
| 1372 |
return int(match.group(1)) if match else None
|
|
@@ -1582,7 +1832,8 @@ def validate_source_verse_alignment(rows_by_base_config: dict[str, list[dict]])
|
|
| 1582 |
for row in rows_by_base_config["verse_sentence"]:
|
| 1583 |
components[row["alignment_component_id"]]["sentences"].append(row)
|
| 1584 |
for row in rows_by_base_config["verse_metre"]:
|
| 1585 |
-
|
|
|
|
| 1586 |
for component in components.values():
|
| 1587 |
sentences = sorted(
|
| 1588 |
component["sentences"], key=lambda row: row["component_sentence_index"],
|
|
@@ -1748,6 +1999,7 @@ def main() -> None:
|
|
| 1748 |
parser.add_argument("--metadata", type=Path, default=Path("metadata"))
|
| 1749 |
parser.add_argument("--metre-output", type=Path, required=True)
|
| 1750 |
parser.add_argument("--metre-metadata", type=Path, required=True)
|
|
|
|
| 1751 |
args = parser.parse_args()
|
| 1752 |
|
| 1753 |
revisions = {
|
|
@@ -1809,7 +2061,7 @@ def main() -> None:
|
|
| 1809 |
sentences, dedup_stats = deduplicate_sentences(sentence_input)
|
| 1810 |
assign_splits(sentences)
|
| 1811 |
|
| 1812 |
-
hyp = load_hypotactic(args.sources / "hypotactic")
|
| 1813 |
verse_input, verse_curation = curate_sentences(agdt_verse + pedalion_verse)
|
| 1814 |
verse_sentence, verse_metre, alignment_stats = align_verse_blocks(
|
| 1815 |
verse_input, hyp, revisions,
|
|
@@ -1817,6 +2069,11 @@ def main() -> None:
|
|
| 1817 |
verse_sentence, verse_metre, passage_curation = exclude_disputed_verse_components(
|
| 1818 |
verse_sentence, verse_metre,
|
| 1819 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1820 |
assign_splits(verse_sentence)
|
| 1821 |
assign_splits(verse_metre)
|
| 1822 |
|
|
@@ -1857,9 +2114,16 @@ def main() -> None:
|
|
| 1857 |
key: {**SOURCE_INFO[key], "revision": revision}
|
| 1858 |
for key, revision in revisions.items()
|
| 1859 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1860 |
sentence_source_revisions = {
|
| 1861 |
key: value for key, value in all_source_revisions.items()
|
| 1862 |
-
if key
|
| 1863 |
}
|
| 1864 |
sentence_report = {
|
| 1865 |
"authorship_curation": {
|
|
@@ -1909,6 +2173,7 @@ def main() -> None:
|
|
| 1909 |
},
|
| 1910 |
"splitting": sentence_report["splitting"],
|
| 1911 |
"alignment": alignment_stats,
|
|
|
|
| 1912 |
"excluded": sentence_report["excluded"],
|
| 1913 |
}
|
| 1914 |
publications = (
|
|
|
|
| 161 |
}
|
| 162 |
|
| 163 |
|
| 164 |
+
# Files predating Hypotactic's embedded data-author/data-work metadata are
|
| 165 |
+
# identified here from their stable upstream filenames. Received or disputed
|
| 166 |
+
# corpora remain explicit so the normal conservative authorship policy can
|
| 167 |
+
# exclude them rather than silently inventing labels.
|
| 168 |
+
HYPOTACTIC_FILE_METADATA = {
|
| 169 |
+
"HHAphrodite": ("Homer/Anon", "Homeric Hymn to Aphrodite"),
|
| 170 |
+
"HHApollo": ("Homer/Anon", "Homeric Hymn to Apollo"),
|
| 171 |
+
"HHDemeter": ("Homer/Anon", "Homeric Hymn to Demeter"),
|
| 172 |
+
"HHermes": ("Homer/Anon", "Homeric Hymn to Hermes"),
|
| 173 |
+
"HHymns": ("Homer/Anon", "The Homeric Hymns"),
|
| 174 |
+
"aratus": ("Aratus", "Phaenomena"),
|
| 175 |
+
"batmumach": ("Pseudo-Homer", "Batrachomyomachia"),
|
| 176 |
+
"cleanthes": ("Cleanthes", "Hymn to Zeus"),
|
| 177 |
+
"colluthus": ("Colluthus", "Rape of Helen"),
|
| 178 |
+
"lycophron": ("Lycophron", "Alexandra"),
|
| 179 |
+
"persians": ("Aeschylus", "Persians"),
|
| 180 |
+
"prometheus": ("Aeschylus", "Prometheus Bound"),
|
| 181 |
+
"scutum": ("Hesiod", "Shield of Heracles"),
|
| 182 |
+
"seven": ("Aeschylus", "Seven Against Thebes"),
|
| 183 |
+
"theognis": ("Theognis", "Theognidea"),
|
| 184 |
+
"theogony": ("Hesiod", "Theogony"),
|
| 185 |
+
"tryph": ("Tryphiodorus", "Sack of Troy"),
|
| 186 |
+
"worksanddays": ("Hesiod", "Works and Days"),
|
| 187 |
+
}
|
| 188 |
+
|
| 189 |
+
HYPOTACTIC_CANONICAL_WORK_IDS = {
|
| 190 |
+
("Aeschylus", "Persians"): "tlg0085.tlg002",
|
| 191 |
+
("Aeschylus", "Prometheus Bound"): "tlg0085.tlg003",
|
| 192 |
+
("Aeschylus", "Seven Against Thebes"): "tlg0085.tlg004",
|
| 193 |
+
("Hesiod", "Theogony"): "tlg0020.tlg001",
|
| 194 |
+
("Hesiod", "Works and Days"): "tlg0020.tlg002",
|
| 195 |
+
("Hesiod", "Shield of Heracles"): "tlg0020.tlg003",
|
| 196 |
+
("Homeric-Iliad", "Iliad"): "tlg0012.tlg001",
|
| 197 |
+
("Homeric-Odyssey", "Odyssey"): "tlg0012.tlg002",
|
| 198 |
+
}
|
| 199 |
+
|
| 200 |
+
|
| 201 |
PEDALION_VERSE = {
|
| 202 |
"achar.xml",
|
| 203 |
"thesmo.xml",
|
|
|
|
| 624 |
author = f"Homeric-{work}"
|
| 625 |
|
| 626 |
lowered_author = author.casefold()
|
| 627 |
+
if author == "Homer/Anon":
|
| 628 |
+
return None, "anonymous_or_received_homeric_hymn"
|
| 629 |
if lowered_author.startswith("unknown"):
|
| 630 |
return None, "unknown_author"
|
| 631 |
if lowered_author.startswith("anonymous"):
|
|
|
|
| 1078 |
self.word_depth = None
|
| 1079 |
self.word_text = []
|
| 1080 |
if self.line_depth == self.depth and tag == "div":
|
| 1081 |
+
self.line["tokens"] = self.line.pop("words")
|
| 1082 |
+
self.line["text"] = " ".join(self.line["tokens"])
|
| 1083 |
symbols = {"long": "–", "short": "⏑", "anceps": "×", "unknown": "?"}
|
| 1084 |
self.line["scansion"] = "".join(symbols[s["quantity"]] for s in self.line["syllables"])
|
| 1085 |
self.line["hypotactic_file"] = self.stem + ".html"
|
|
|
|
| 1090 |
"poem_sequence": self.poem.get("sequence", "1"),
|
| 1091 |
})
|
| 1092 |
if self.line["text"] and self.line["number"]:
|
| 1093 |
+
self.line["line_sequence"] = str(len(self.lines) + 1)
|
| 1094 |
self.lines.append(self.line)
|
| 1095 |
self.line = None
|
| 1096 |
self.line_depth = None
|
|
|
|
| 1104 |
parser = HypotacticParser(path.stem)
|
| 1105 |
parser.feed(path.read_text(encoding="utf8"))
|
| 1106 |
# Older files do not carry book metadata; recover it from their stem.
|
| 1107 |
+
book_match = re.match(
|
| 1108 |
+
r"(?:apollonius|iliad|odyssey|dionysiaca|qsmyrnaeus)(\d+)$",
|
| 1109 |
+
path.stem,
|
| 1110 |
+
)
|
| 1111 |
for line in parser.lines:
|
| 1112 |
if not line["book"] and book_match:
|
| 1113 |
line["book"] = book_match.group(1)
|
|
|
|
| 1115 |
return parser.lines
|
| 1116 |
|
| 1117 |
|
| 1118 |
+
def load_hypotactic(root: Path, *, all_files: bool = False) -> dict[str, list[dict]]:
|
| 1119 |
html_root = root / "hypotactic_htmls_greek"
|
| 1120 |
+
needed = (
|
| 1121 |
+
sorted(path.stem for path in html_root.glob("*.html"))
|
| 1122 |
+
if all_files
|
| 1123 |
+
else sorted({stem for link in VERSE_LINKS.values() for stem in link["files"]})
|
| 1124 |
+
)
|
| 1125 |
return {stem: parse_hypotactic_file(html_root / f"{stem}.html") for stem in needed}
|
| 1126 |
|
| 1127 |
|
| 1128 |
+
def hypotactic_author_work(stem: str, line: dict) -> tuple[str, str, str]:
|
| 1129 |
+
"""Return curated upstream author/work labels and a stable work ID."""
|
| 1130 |
+
if re.fullmatch(r"apollonius\d+", stem):
|
| 1131 |
+
author, work = "Apollonius Rhodius", "Argonautica"
|
| 1132 |
+
elif re.fullmatch(r"iliad\d+", stem):
|
| 1133 |
+
author, work = "Homer", "Iliad"
|
| 1134 |
+
elif re.fullmatch(r"odyssey\d+", stem):
|
| 1135 |
+
author, work = "Homer", "Odyssey"
|
| 1136 |
+
else:
|
| 1137 |
+
author = line.get("hypotactic_author", "").strip()
|
| 1138 |
+
work = line.get("hypotactic_work", "").strip()
|
| 1139 |
+
fallback = HYPOTACTIC_FILE_METADATA.get(stem)
|
| 1140 |
+
if fallback and stem in {"persians", "seven"}:
|
| 1141 |
+
author, work = fallback
|
| 1142 |
+
if fallback:
|
| 1143 |
+
author = author or fallback[0]
|
| 1144 |
+
work = work or fallback[1]
|
| 1145 |
+
if not work:
|
| 1146 |
+
work = {
|
| 1147 |
+
"Moschus": "Poems", "Semonides": "Fragments",
|
| 1148 |
+
"Solon": "Fragments", "Tyrtaeus": "Elegies",
|
| 1149 |
+
}.get(author, stem)
|
| 1150 |
+
author = canonical_author(author)
|
| 1151 |
+
if author == "Homer" and work in {"Iliad", "Odyssey"}:
|
| 1152 |
+
author = f"Homeric-{work}"
|
| 1153 |
+
work_id = HYPOTACTIC_CANONICAL_WORK_IDS.get(
|
| 1154 |
+
(author, work), f"hypotactic:{slug(author)}:{slug(work)}",
|
| 1155 |
+
)
|
| 1156 |
+
return author, work, work_id
|
| 1157 |
+
|
| 1158 |
+
|
| 1159 |
+
def hypotactic_line_key(line: dict) -> tuple[str, str, str, str, str]:
|
| 1160 |
+
return (
|
| 1161 |
+
line["hypotactic_file"], line["poem_sequence"], line["book"],
|
| 1162 |
+
line["number"], line["line_sequence"],
|
| 1163 |
+
)
|
| 1164 |
+
|
| 1165 |
+
|
| 1166 |
+
def curated_hypotactic_line(stem: str, line: dict) -> tuple[dict | None, str | None]:
|
| 1167 |
+
if not any("GREEK" in unicodedata.name(char, "") for char in line["text"]):
|
| 1168 |
+
return None, "no_greek_letters"
|
| 1169 |
+
author, work, work_id = hypotactic_author_work(stem, line)
|
| 1170 |
+
curated_author, reason = authorship_decision(Sentence(
|
| 1171 |
+
source="hypotactic", source_file=f"{stem}.html",
|
| 1172 |
+
source_sentence_id=":".join(hypotactic_line_key(line)),
|
| 1173 |
+
author=author, work=work, work_id=work_id, text=line["text"], conllu="",
|
| 1174 |
+
genre="verse",
|
| 1175 |
+
))
|
| 1176 |
+
if reason:
|
| 1177 |
+
return None, reason
|
| 1178 |
+
return {
|
| 1179 |
+
"author": curated_author, "work": work, "work_id": work_id,
|
| 1180 |
+
"text": line["text"], "tokens": line["tokens"],
|
| 1181 |
+
}, None
|
| 1182 |
+
|
| 1183 |
+
|
| 1184 |
def verse_sentence_order_key(sentence: Sentence) -> tuple:
|
| 1185 |
references = []
|
| 1186 |
for cite in sentence.native_cites:
|
|
|
|
| 1280 |
source_record(
|
| 1281 |
"hypotactic", revisions, source_file,
|
| 1282 |
",".join(
|
| 1283 |
+
f"{line['poem_sequence']}:{line['book']}:{line['number']}:{line['line_sequence']}"
|
| 1284 |
for line in file_lines
|
| 1285 |
),
|
| 1286 |
)
|
|
|
|
| 1471 |
return sentence_rows, metre_rows, alignment_stats
|
| 1472 |
|
| 1473 |
|
| 1474 |
+
STOICHEIA_MODEL_ID = "Ericu950/Stoicheia-tagger-parser"
|
| 1475 |
+
STOICHEIA_MODEL_REVISION = "cd8ae1658c364874c3b6f4df37bd1d46313e3cea"
|
| 1476 |
+
|
| 1477 |
+
|
| 1478 |
+
def load_stoicheia_predictions(path: Path) -> dict[tuple[str, ...], dict]:
|
| 1479 |
+
predictions = {}
|
| 1480 |
+
with path.open(encoding="utf-8") as handle:
|
| 1481 |
+
for number, raw in enumerate(handle, 1):
|
| 1482 |
+
try:
|
| 1483 |
+
row = json.loads(raw)
|
| 1484 |
+
except json.JSONDecodeError as error:
|
| 1485 |
+
raise ValueError(f"invalid Stoicheia JSONL line {number}") from error
|
| 1486 |
+
key = tuple(row["key"])
|
| 1487 |
+
if key in predictions:
|
| 1488 |
+
raise ValueError(f"duplicate Stoicheia prediction key: {key}")
|
| 1489 |
+
if row["model"] != STOICHEIA_MODEL_ID:
|
| 1490 |
+
raise ValueError(f"unexpected Stoicheia model at line {number}")
|
| 1491 |
+
if row["model_revision"] != STOICHEIA_MODEL_REVISION:
|
| 1492 |
+
raise ValueError(f"unexpected Stoicheia revision at line {number}")
|
| 1493 |
+
predictions[key] = row
|
| 1494 |
+
return predictions
|
| 1495 |
+
|
| 1496 |
+
|
| 1497 |
+
def stoicheia_source_record() -> dict:
|
| 1498 |
+
return {
|
| 1499 |
+
"source": "stoicheia_tagger_parser",
|
| 1500 |
+
"source_file": STOICHEIA_MODEL_ID,
|
| 1501 |
+
"source_sentence_id": "",
|
| 1502 |
+
"url": f"https://huggingface.co/{STOICHEIA_MODEL_ID}",
|
| 1503 |
+
"revision": STOICHEIA_MODEL_REVISION,
|
| 1504 |
+
"license": "Apache-2.0",
|
| 1505 |
+
"annotation_provenance": (
|
| 1506 |
+
"automatic lemma, POS, morphology, and dependency prediction"
|
| 1507 |
+
),
|
| 1508 |
+
"syntax_scheme": "Stoicheia AGDT heads converted to Universal Dependencies",
|
| 1509 |
+
}
|
| 1510 |
+
|
| 1511 |
+
|
| 1512 |
+
def predicted_metre_rows(
|
| 1513 |
+
all_hypotactic: dict[str, list[dict]],
|
| 1514 |
+
predictions: dict[tuple[str, ...], dict],
|
| 1515 |
+
gold_rows: list[dict],
|
| 1516 |
+
revisions: dict[str, str],
|
| 1517 |
+
) -> tuple[list[dict], dict]:
|
| 1518 |
+
"""Fill lines without a gold tree with pinned Stoicheia predictions."""
|
| 1519 |
+
lines_by_key = {
|
| 1520 |
+
hypotactic_line_key(line): line
|
| 1521 |
+
for lines in all_hypotactic.values()
|
| 1522 |
+
for line in lines
|
| 1523 |
+
}
|
| 1524 |
+
eligible = {}
|
| 1525 |
+
excluded = Counter()
|
| 1526 |
+
for stem, lines in all_hypotactic.items():
|
| 1527 |
+
for line in lines:
|
| 1528 |
+
curated, reason = curated_hypotactic_line(stem, line)
|
| 1529 |
+
if reason:
|
| 1530 |
+
excluded[reason] += 1
|
| 1531 |
+
else:
|
| 1532 |
+
eligible[hypotactic_line_key(line)] = curated
|
| 1533 |
+
if set(predictions) != set(eligible):
|
| 1534 |
+
missing = set(eligible) - set(predictions)
|
| 1535 |
+
extra = set(predictions) - set(eligible)
|
| 1536 |
+
raise ValueError(
|
| 1537 |
+
f"Stoicheia cache is incomplete or stale: missing={len(missing)} extra={len(extra)}"
|
| 1538 |
+
)
|
| 1539 |
+
gold_keys = {
|
| 1540 |
+
(row["hypotactic_file"], row["poem_sequence"], row["book"], row["line_number"])
|
| 1541 |
+
for row in gold_rows
|
| 1542 |
+
}
|
| 1543 |
+
output = []
|
| 1544 |
+
excluded_disputed = 0
|
| 1545 |
+
for key, prediction in sorted(predictions.items()):
|
| 1546 |
+
if key[:4] in gold_keys:
|
| 1547 |
+
continue
|
| 1548 |
+
line = lines_by_key.get(key)
|
| 1549 |
+
if line is None:
|
| 1550 |
+
raise ValueError(f"Stoicheia prediction has no Hypotactic line: {key}")
|
| 1551 |
+
if normalize(prediction["text"]) != line["normalized"]:
|
| 1552 |
+
raise ValueError(f"Stoicheia prediction text drifted from Hypotactic: {key}")
|
| 1553 |
+
author = eligible[key]["author"]
|
| 1554 |
+
work = eligible[key]["work"]
|
| 1555 |
+
work_id = eligible[key]["work_id"]
|
| 1556 |
+
if (prediction["author"], prediction["work"]) != (author, work):
|
| 1557 |
+
raise ValueError(f"Stoicheia prediction authorship drifted: {key}")
|
| 1558 |
+
line_number = numeric_line_number(line["number"])
|
| 1559 |
+
if line_number is not None and any(
|
| 1560 |
+
start <= line_number <= end
|
| 1561 |
+
for start, end in DISPUTED_VERSE_PASSAGES.get((author, work), ())
|
| 1562 |
+
):
|
| 1563 |
+
excluded_disputed += 1
|
| 1564 |
+
continue
|
| 1565 |
+
hyp_record = hypotactic_source_records([line], revisions)[0]
|
| 1566 |
+
model_record = stoicheia_source_record()
|
| 1567 |
+
records = [hyp_record, model_record]
|
| 1568 |
+
output.append({
|
| 1569 |
+
"id": "vm-" + stable_id(work_id, *key),
|
| 1570 |
+
"parent_sentence_ids": [],
|
| 1571 |
+
"author": author,
|
| 1572 |
+
"work": work,
|
| 1573 |
+
"work_id": work_id,
|
| 1574 |
+
"genre": "verse_metre",
|
| 1575 |
+
"text": line["text"],
|
| 1576 |
+
"conllu": prediction["conllu"],
|
| 1577 |
+
"cts_urn": "",
|
| 1578 |
+
"passage": line["number"],
|
| 1579 |
+
"alignment_component_id": None,
|
| 1580 |
+
"component_line_index": None,
|
| 1581 |
+
"book": line["book"],
|
| 1582 |
+
"poem_sequence": line["poem_sequence"],
|
| 1583 |
+
"line_number": line["number"],
|
| 1584 |
+
"metre": line["metre"] or "unspecified",
|
| 1585 |
+
"syllables": json.dumps(line["syllables"], ensure_ascii=False),
|
| 1586 |
+
"hypotactic_file": line["hypotactic_file"],
|
| 1587 |
+
"treebank_source": "stoicheia_tagger_parser",
|
| 1588 |
+
"syntax_annotation": "predicted",
|
| 1589 |
+
"source_records": json.dumps(records, ensure_ascii=False, sort_keys=True),
|
| 1590 |
+
"licenses": sorted({record["license"] for record in records}),
|
| 1591 |
+
"dedup_key": hashlib.sha256(line["normalized"].encode()).hexdigest(),
|
| 1592 |
+
})
|
| 1593 |
+
for row in gold_rows:
|
| 1594 |
+
row["syntax_annotation"] = "gold"
|
| 1595 |
+
return output, {
|
| 1596 |
+
"model": STOICHEIA_MODEL_ID,
|
| 1597 |
+
"model_revision": STOICHEIA_MODEL_REVISION,
|
| 1598 |
+
"predictions_in_cache": len(predictions),
|
| 1599 |
+
"hypotactic_lines_total": len(lines_by_key),
|
| 1600 |
+
"hypotactic_lines_excluded_before_parsing": sum(excluded.values()),
|
| 1601 |
+
"hypotactic_lines_excluded_by_reason": dict(sorted(excluded.items())),
|
| 1602 |
+
"gold_lines": len(gold_rows),
|
| 1603 |
+
"gold_keys": len(gold_keys),
|
| 1604 |
+
"predicted_lines_added": len(output),
|
| 1605 |
+
"predictions_superseded_by_gold": sum(key[:4] in gold_keys for key in predictions),
|
| 1606 |
+
"predicted_disputed_lines_excluded": excluded_disputed,
|
| 1607 |
+
"predicted_head_repair_tokens": sum(
|
| 1608 |
+
line.endswith("\tHeadRepair=Yes")
|
| 1609 |
+
for row in output
|
| 1610 |
+
for line in row["conllu"].splitlines()
|
| 1611 |
+
),
|
| 1612 |
+
"predicted_tokens": sum(
|
| 1613 |
+
bool(line) and not line.startswith("#")
|
| 1614 |
+
for row in output
|
| 1615 |
+
for line in row["conllu"].splitlines()
|
| 1616 |
+
),
|
| 1617 |
+
}
|
| 1618 |
+
|
| 1619 |
+
|
| 1620 |
def numeric_line_number(value: str) -> int | None:
|
| 1621 |
match = re.match(r"^(\d+)", str(value))
|
| 1622 |
return int(match.group(1)) if match else None
|
|
|
|
| 1832 |
for row in rows_by_base_config["verse_sentence"]:
|
| 1833 |
components[row["alignment_component_id"]]["sentences"].append(row)
|
| 1834 |
for row in rows_by_base_config["verse_metre"]:
|
| 1835 |
+
if row["alignment_component_id"] is not None:
|
| 1836 |
+
components[row["alignment_component_id"]]["lines"].append(row)
|
| 1837 |
for component in components.values():
|
| 1838 |
sentences = sorted(
|
| 1839 |
component["sentences"], key=lambda row: row["component_sentence_index"],
|
|
|
|
| 1999 |
parser.add_argument("--metadata", type=Path, default=Path("metadata"))
|
| 2000 |
parser.add_argument("--metre-output", type=Path, required=True)
|
| 2001 |
parser.add_argument("--metre-metadata", type=Path, required=True)
|
| 2002 |
+
parser.add_argument("--stoicheia-conllu", type=Path, required=True)
|
| 2003 |
args = parser.parse_args()
|
| 2004 |
|
| 2005 |
revisions = {
|
|
|
|
| 2061 |
sentences, dedup_stats = deduplicate_sentences(sentence_input)
|
| 2062 |
assign_splits(sentences)
|
| 2063 |
|
| 2064 |
+
hyp = load_hypotactic(args.sources / "hypotactic", all_files=True)
|
| 2065 |
verse_input, verse_curation = curate_sentences(agdt_verse + pedalion_verse)
|
| 2066 |
verse_sentence, verse_metre, alignment_stats = align_verse_blocks(
|
| 2067 |
verse_input, hyp, revisions,
|
|
|
|
| 2069 |
verse_sentence, verse_metre, passage_curation = exclude_disputed_verse_components(
|
| 2070 |
verse_sentence, verse_metre,
|
| 2071 |
)
|
| 2072 |
+
stoicheia_predictions = load_stoicheia_predictions(args.stoicheia_conllu)
|
| 2073 |
+
predicted_metre, stoicheia_stats = predicted_metre_rows(
|
| 2074 |
+
hyp, stoicheia_predictions, verse_metre, revisions,
|
| 2075 |
+
)
|
| 2076 |
+
verse_metre.extend(predicted_metre)
|
| 2077 |
assign_splits(verse_sentence)
|
| 2078 |
assign_splits(verse_metre)
|
| 2079 |
|
|
|
|
| 2114 |
key: {**SOURCE_INFO[key], "revision": revision}
|
| 2115 |
for key, revision in revisions.items()
|
| 2116 |
}
|
| 2117 |
+
all_source_revisions["stoicheia_tagger_parser"] = {
|
| 2118 |
+
"url": f"https://huggingface.co/{STOICHEIA_MODEL_ID}",
|
| 2119 |
+
"license": "Apache-2.0",
|
| 2120 |
+
"annotation": "automatic morphosyntactic and dependency annotation",
|
| 2121 |
+
"scheme": "Stoicheia AGDT heads converted to Universal Dependencies",
|
| 2122 |
+
"revision": STOICHEIA_MODEL_REVISION,
|
| 2123 |
+
}
|
| 2124 |
sentence_source_revisions = {
|
| 2125 |
key: value for key, value in all_source_revisions.items()
|
| 2126 |
+
if key not in {"hypotactic", "stoicheia_tagger_parser"}
|
| 2127 |
}
|
| 2128 |
sentence_report = {
|
| 2129 |
"authorship_curation": {
|
|
|
|
| 2173 |
},
|
| 2174 |
"splitting": sentence_report["splitting"],
|
| 2175 |
"alignment": alignment_stats,
|
| 2176 |
+
"automatic_syntax": stoicheia_stats,
|
| 2177 |
"excluded": sentence_report["excluded"],
|
| 2178 |
}
|
| 2179 |
publications = (
|
scripts/dataset_variants.py
CHANGED
|
@@ -143,6 +143,7 @@ def _provenance(row: dict) -> dict:
|
|
| 143 |
keys = (
|
| 144 |
"id", "work", "work_id", "cts_urn", "passage", "treebank_source",
|
| 145 |
"book", "poem_sequence", "line_number", "hypotactic_file",
|
|
|
|
| 146 |
)
|
| 147 |
return {key: row.get(key) for key in keys if key in row}
|
| 148 |
|
|
@@ -247,6 +248,10 @@ def _aggregate_chunk(base_config: str, rows: list[dict], target: int, split: str
|
|
| 247 |
rows[0]["hypotactic_file"]
|
| 248 |
if len({row["hypotactic_file"] for row in rows}) == 1 else None
|
| 249 |
),
|
|
|
|
|
|
|
|
|
|
|
|
|
| 250 |
})
|
| 251 |
return chunk
|
| 252 |
|
|
@@ -306,6 +311,11 @@ def make_dataset_variants(
|
|
| 306 |
"row_unit": "line" if base_config == "verse_metre" else "sentence",
|
| 307 |
"shared_source_selection_target": BOTTLENECK_TARGET,
|
| 308 |
"discarded_source_row_ids": bottleneck_discarded,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 309 |
}
|
| 310 |
for target in CHUNK_TARGETS:
|
| 311 |
config = f"{base_config}_{target}"
|
|
@@ -348,5 +358,10 @@ def make_dataset_variants(
|
|
| 348 |
},
|
| 349 |
"mixed_work_chunks": dict(mixed_work_chunks),
|
| 350 |
"chunking_seed": CHUNKING_SEED,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 351 |
}
|
| 352 |
return variants, report
|
|
|
|
| 143 |
keys = (
|
| 144 |
"id", "work", "work_id", "cts_urn", "passage", "treebank_source",
|
| 145 |
"book", "poem_sequence", "line_number", "hypotactic_file",
|
| 146 |
+
"syntax_annotation",
|
| 147 |
)
|
| 148 |
return {key: row.get(key) for key in keys if key in row}
|
| 149 |
|
|
|
|
| 248 |
rows[0]["hypotactic_file"]
|
| 249 |
if len({row["hypotactic_file"] for row in rows}) == 1 else None
|
| 250 |
),
|
| 251 |
+
"syntax_annotation": (
|
| 252 |
+
rows[0]["syntax_annotation"]
|
| 253 |
+
if len({row["syntax_annotation"] for row in rows}) == 1 else "mixed"
|
| 254 |
+
),
|
| 255 |
})
|
| 256 |
return chunk
|
| 257 |
|
|
|
|
| 311 |
"row_unit": "line" if base_config == "verse_metre" else "sentence",
|
| 312 |
"shared_source_selection_target": BOTTLENECK_TARGET,
|
| 313 |
"discarded_source_row_ids": bottleneck_discarded,
|
| 314 |
+
**({
|
| 315 |
+
"syntax_annotations": dict(Counter(
|
| 316 |
+
row["syntax_annotation"] for row in shared_rows
|
| 317 |
+
)),
|
| 318 |
+
} if base_config == "verse_metre" else {}),
|
| 319 |
}
|
| 320 |
for target in CHUNK_TARGETS:
|
| 321 |
config = f"{base_config}_{target}"
|
|
|
|
| 358 |
},
|
| 359 |
"mixed_work_chunks": dict(mixed_work_chunks),
|
| 360 |
"chunking_seed": CHUNKING_SEED,
|
| 361 |
+
**({
|
| 362 |
+
"syntax_annotations": dict(Counter(
|
| 363 |
+
row["syntax_annotation"] for row in variant_rows
|
| 364 |
+
)),
|
| 365 |
+
} if base_config == "verse_metre" else {}),
|
| 366 |
}
|
| 367 |
return variants, report
|
scripts/stoicheia_parse_hypotactic.py
ADDED
|
@@ -0,0 +1,247 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Create resumable Stoicheia CoNLL-U predictions for curated Hypotactic lines."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
import json
|
| 8 |
+
import os
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
import sys
|
| 11 |
+
import time
|
| 12 |
+
import unicodedata
|
| 13 |
+
|
| 14 |
+
import torch
|
| 15 |
+
from huggingface_hub import snapshot_download
|
| 16 |
+
from transformers import AutoModel
|
| 17 |
+
|
| 18 |
+
try:
|
| 19 |
+
from scripts.build_dataset import (
|
| 20 |
+
curated_hypotactic_line,
|
| 21 |
+
hypotactic_line_key,
|
| 22 |
+
load_hypotactic,
|
| 23 |
+
normalize,
|
| 24 |
+
)
|
| 25 |
+
except ModuleNotFoundError:
|
| 26 |
+
from build_dataset import (
|
| 27 |
+
curated_hypotactic_line,
|
| 28 |
+
hypotactic_line_key,
|
| 29 |
+
load_hypotactic,
|
| 30 |
+
normalize,
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
MODEL_ID = "Ericu950/Stoicheia-tagger-parser"
|
| 35 |
+
MODEL_REVISION = "cd8ae1658c364874c3b6f4df37bd1d46313e3cea"
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def retained_line(stem: str, line: dict) -> dict | None:
|
| 39 |
+
curated, reason = curated_hypotactic_line(stem, line)
|
| 40 |
+
if reason:
|
| 41 |
+
return None
|
| 42 |
+
return {
|
| 43 |
+
"key": list(hypotactic_line_key(line)),
|
| 44 |
+
**curated,
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def load_completed(path: Path) -> set[tuple[str, ...]]:
|
| 49 |
+
completed = set()
|
| 50 |
+
if not path.exists():
|
| 51 |
+
return completed
|
| 52 |
+
with path.open(encoding="utf-8") as handle:
|
| 53 |
+
for number, raw in enumerate(handle, 1):
|
| 54 |
+
try:
|
| 55 |
+
row = json.loads(raw)
|
| 56 |
+
except json.JSONDecodeError as error:
|
| 57 |
+
raise ValueError(f"invalid checkpoint JSON at line {number}") from error
|
| 58 |
+
completed.add(tuple(row["key"]))
|
| 59 |
+
return completed
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def repair_tree(words: list[dict]) -> list[dict]:
|
| 63 |
+
"""Make the greedy biaffine decode a single rooted, acyclic UD tree."""
|
| 64 |
+
if not words:
|
| 65 |
+
raise ValueError("Stoicheia decoded no Greek tokens")
|
| 66 |
+
n = len(words)
|
| 67 |
+
original = [(int(word.get("head") or 0), word.get("deprel")) for word in words]
|
| 68 |
+
heads = [int(word.get("head") or 0) for word in words]
|
| 69 |
+
roots = [
|
| 70 |
+
index for index, (word, head) in enumerate(zip(words, heads), 1)
|
| 71 |
+
if head == 0 and word["upos"] != "PUNCT"
|
| 72 |
+
]
|
| 73 |
+
primary = roots[0] if roots else next(
|
| 74 |
+
(index for index, word in enumerate(words, 1) if word["upos"] != "PUNCT"), 1,
|
| 75 |
+
)
|
| 76 |
+
for index, word in enumerate(words, 1):
|
| 77 |
+
head = heads[index - 1]
|
| 78 |
+
if index == primary:
|
| 79 |
+
heads[index - 1] = 0
|
| 80 |
+
word["deprel"] = "root"
|
| 81 |
+
elif head < 0 or head > n or head in {0, index}:
|
| 82 |
+
heads[index - 1] = primary
|
| 83 |
+
word["deprel"] = "punct" if word["upos"] == "PUNCT" else "dep"
|
| 84 |
+
elif word.get("deprel") == "root":
|
| 85 |
+
word["deprel"] = "dep"
|
| 86 |
+
|
| 87 |
+
changed = True
|
| 88 |
+
while changed:
|
| 89 |
+
changed = False
|
| 90 |
+
for token_id in range(1, n + 1):
|
| 91 |
+
trail = []
|
| 92 |
+
cursor = token_id
|
| 93 |
+
while cursor:
|
| 94 |
+
if cursor in trail:
|
| 95 |
+
cycle = trail[trail.index(cursor):]
|
| 96 |
+
break_id = min(cycle)
|
| 97 |
+
heads[break_id - 1] = 0 if break_id == primary else primary
|
| 98 |
+
words[break_id - 1]["deprel"] = (
|
| 99 |
+
"root" if break_id == primary else "dep"
|
| 100 |
+
)
|
| 101 |
+
changed = True
|
| 102 |
+
break
|
| 103 |
+
trail.append(cursor)
|
| 104 |
+
cursor = heads[cursor - 1]
|
| 105 |
+
if changed:
|
| 106 |
+
break
|
| 107 |
+
for word, head, (old_head, old_deprel) in zip(words, heads, original):
|
| 108 |
+
word["head"] = head
|
| 109 |
+
word["head_repair"] = head != old_head or word.get("deprel") != old_deprel
|
| 110 |
+
return words
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def restore_alphabetic_non_greek_tokens(
|
| 114 |
+
tokens: list[str], words: list[dict],
|
| 115 |
+
) -> list[dict]:
|
| 116 |
+
"""Restore alphabetic tokens the character model intentionally omits."""
|
| 117 |
+
old_to_new = {}
|
| 118 |
+
merged = []
|
| 119 |
+
decoded_index = 0
|
| 120 |
+
for token in tokens:
|
| 121 |
+
has_greek = any("GREEK" in unicodedata.name(char, "") for char in token)
|
| 122 |
+
if has_greek:
|
| 123 |
+
if decoded_index >= len(words) or words[decoded_index]["form"] != token:
|
| 124 |
+
raise ValueError("Stoicheia form order differs from Hypotactic tokens")
|
| 125 |
+
decoded_index += 1
|
| 126 |
+
old_to_new[decoded_index] = len(merged) + 1
|
| 127 |
+
merged.append(dict(words[decoded_index - 1]))
|
| 128 |
+
elif normalize(token):
|
| 129 |
+
merged.append({
|
| 130 |
+
"form": token, "lemma": token, "upos": "X", "xpos": "x--------",
|
| 131 |
+
"feats": {}, "head": 0, "deprel": "dep", "_restored": True,
|
| 132 |
+
})
|
| 133 |
+
if decoded_index != len(words):
|
| 134 |
+
raise ValueError("Stoicheia returned unexpected extra forms")
|
| 135 |
+
for word in merged:
|
| 136 |
+
if word.pop("_restored", False):
|
| 137 |
+
continue
|
| 138 |
+
if word.get("head"):
|
| 139 |
+
word["head"] = old_to_new[word["head"]]
|
| 140 |
+
return merged
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def encode_conllu(text: str, tokens: list[str], words: list[dict]) -> str:
|
| 144 |
+
words = restore_alphabetic_non_greek_tokens(tokens, words)
|
| 145 |
+
words = repair_tree(words)
|
| 146 |
+
lines = [f"# text = {text}"]
|
| 147 |
+
for index, word in enumerate(words, 1):
|
| 148 |
+
feats = word.get("feats") or {}
|
| 149 |
+
feat_text = "|".join(f"{key}={feats[key]}" for key in sorted(feats)) or "_"
|
| 150 |
+
lines.append("\t".join([
|
| 151 |
+
str(index), word["form"], word.get("lemma") or "_",
|
| 152 |
+
word.get("upos") or "X", word.get("xpos") or "_", feat_text,
|
| 153 |
+
str(word["head"]), word.get("deprel") or "dep", "_",
|
| 154 |
+
"HeadRepair=Yes" if word["head_repair"] else "_",
|
| 155 |
+
]))
|
| 156 |
+
conllu = "\n".join(lines) + "\n\n"
|
| 157 |
+
forms = "".join(word["form"] for word in words)
|
| 158 |
+
if normalize(forms) != normalize(text):
|
| 159 |
+
raise ValueError("Stoicheia forms do not cover the Hypotactic line")
|
| 160 |
+
return conllu
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def main() -> None:
|
| 164 |
+
parser = argparse.ArgumentParser()
|
| 165 |
+
parser.add_argument("--hypotactic", type=Path, required=True)
|
| 166 |
+
parser.add_argument("--output", type=Path, required=True)
|
| 167 |
+
parser.add_argument("--batch-size", type=int, default=64)
|
| 168 |
+
parser.add_argument("--log-every", type=int, default=1024)
|
| 169 |
+
args = parser.parse_args()
|
| 170 |
+
|
| 171 |
+
all_lines = load_hypotactic(args.hypotactic, all_files=True)
|
| 172 |
+
retained = [
|
| 173 |
+
row
|
| 174 |
+
for stem, lines in sorted(all_lines.items())
|
| 175 |
+
for line in lines
|
| 176 |
+
if (row := retained_line(stem, line)) is not None
|
| 177 |
+
]
|
| 178 |
+
keys = [tuple(row["key"]) for row in retained]
|
| 179 |
+
if len(keys) != len(set(keys)):
|
| 180 |
+
raise ValueError("Hypotactic line keys are not unique")
|
| 181 |
+
|
| 182 |
+
args.output.parent.mkdir(parents=True, exist_ok=True)
|
| 183 |
+
completed = load_completed(args.output)
|
| 184 |
+
pending = [row for row in retained if tuple(row["key"]) not in completed]
|
| 185 |
+
print(
|
| 186 |
+
f"inventory retained={len(retained)} completed={len(completed)} "
|
| 187 |
+
f"pending={len(pending)} model={MODEL_ID}@{MODEL_REVISION}",
|
| 188 |
+
flush=True,
|
| 189 |
+
)
|
| 190 |
+
if not pending:
|
| 191 |
+
return
|
| 192 |
+
|
| 193 |
+
local = snapshot_download(
|
| 194 |
+
MODEL_ID, revision=MODEL_REVISION,
|
| 195 |
+
allow_patterns=["*.json", "*.txt", "*.py", "*.model", "*.safetensors"],
|
| 196 |
+
)
|
| 197 |
+
sys.path.insert(0, local)
|
| 198 |
+
from processing_char_bert_joint import CharBertJointProcessor
|
| 199 |
+
|
| 200 |
+
device = torch.device("cuda")
|
| 201 |
+
model = AutoModel.from_pretrained(
|
| 202 |
+
local, trust_remote_code=True, dtype=torch.bfloat16,
|
| 203 |
+
).to(device).eval()
|
| 204 |
+
processor = CharBertJointProcessor.from_pretrained(local)
|
| 205 |
+
print(
|
| 206 |
+
f"loaded model device={device} dtype={next(model.parameters()).dtype} "
|
| 207 |
+
f"batch_size={args.batch_size}",
|
| 208 |
+
flush=True,
|
| 209 |
+
)
|
| 210 |
+
|
| 211 |
+
started = time.monotonic()
|
| 212 |
+
with args.output.open("a", encoding="utf-8", buffering=1) as handle:
|
| 213 |
+
for start in range(0, len(pending), args.batch_size):
|
| 214 |
+
items = pending[start:start + args.batch_size]
|
| 215 |
+
batch = processor([item["tokens"] for item in items])
|
| 216 |
+
model_batch = {
|
| 217 |
+
key: value.to(device, non_blocking=True)
|
| 218 |
+
for key, value in batch.items() if not key.startswith("_")
|
| 219 |
+
}
|
| 220 |
+
with torch.inference_mode():
|
| 221 |
+
output = model(**model_batch)
|
| 222 |
+
decoded = processor.decode(output, batch, ud=True)
|
| 223 |
+
if len(decoded) != len(items):
|
| 224 |
+
raise RuntimeError("Stoicheia returned the wrong batch cardinality")
|
| 225 |
+
for item, words in zip(items, decoded):
|
| 226 |
+
result = {
|
| 227 |
+
**{key: item[key] for key in ("key", "author", "work", "work_id", "text")},
|
| 228 |
+
"conllu": encode_conllu(item["text"], item["tokens"], words),
|
| 229 |
+
"model": MODEL_ID,
|
| 230 |
+
"model_revision": MODEL_REVISION,
|
| 231 |
+
}
|
| 232 |
+
handle.write(json.dumps(result, ensure_ascii=False, sort_keys=True) + "\n")
|
| 233 |
+
handle.flush()
|
| 234 |
+
os.fsync(handle.fileno())
|
| 235 |
+
done = start + len(items)
|
| 236 |
+
if done == len(pending) or done % args.log_every < args.batch_size:
|
| 237 |
+
elapsed = time.monotonic() - started
|
| 238 |
+
rate = done / elapsed if elapsed else 0
|
| 239 |
+
print(
|
| 240 |
+
f"progress new={done}/{len(pending)} total={len(completed) + done}/"
|
| 241 |
+
f"{len(retained)} rate={rate:.1f}_lines_s elapsed={elapsed:.1f}s",
|
| 242 |
+
flush=True,
|
| 243 |
+
)
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
if __name__ == "__main__":
|
| 247 |
+
main()
|
slurm/rebuild_dataset.slurm
CHANGED
|
@@ -19,6 +19,7 @@ repo=/nobackup/proj/flash/dionysus/personal/cleland/sphragis
|
|
| 19 |
metre_repo=/nobackup/proj/flash/dionysus/personal/cleland/sphragis-metre
|
| 20 |
sources=/nobackup/proj/flash/dionysus/personal/cleland/.sphregis-investigation.VmoHEE
|
| 21 |
python=/nobackup/proj/flash/dionysus/personal/cleland/.venv-sphregis-build-gpu/bin/python
|
|
|
|
| 22 |
stage="${repo}/.build-stage-${SLURM_JOB_ID}"
|
| 23 |
backup="${repo}/.build-backup-${SLURM_JOB_ID}"
|
| 24 |
metre_stage="${metre_repo}/.build-stage-${SLURM_JOB_ID}"
|
|
@@ -29,12 +30,14 @@ echo "[$(date --iso-8601=seconds)] host=$(hostname) job=${SLURM_JOB_ID} stage=${
|
|
| 29 |
test -x "$python"
|
| 30 |
test -d "$sources"
|
| 31 |
test -d "$metre_repo/.git"
|
|
|
|
| 32 |
mkdir -p "$stage" "$backup" "$metre_stage" "$metre_backup"
|
| 33 |
|
| 34 |
echo "[$(date --iso-8601=seconds)] rebuilding all configurations from pinned sources"
|
| 35 |
srun --kill-on-bad-exit=1 "$python" -u scripts/build_dataset.py \
|
| 36 |
--sources "$sources" --output "$stage/data" --metadata "$stage/metadata" \
|
| 37 |
-
--metre-output "$metre_stage/data" --metre-metadata "$metre_stage/metadata"
|
|
|
|
| 38 |
|
| 39 |
echo "[$(date --iso-8601=seconds)] independently validating both staged publications"
|
| 40 |
srun --kill-on-bad-exit=1 "$python" -u scripts/validate_publication.py \
|
|
|
|
| 19 |
metre_repo=/nobackup/proj/flash/dionysus/personal/cleland/sphragis-metre
|
| 20 |
sources=/nobackup/proj/flash/dionysus/personal/cleland/.sphregis-investigation.VmoHEE
|
| 21 |
python=/nobackup/proj/flash/dionysus/personal/cleland/.venv-sphregis-build-gpu/bin/python
|
| 22 |
+
stoicheia_conllu="${repo}/.stoicheia-cache/hypotactic_conllu.jsonl"
|
| 23 |
stage="${repo}/.build-stage-${SLURM_JOB_ID}"
|
| 24 |
backup="${repo}/.build-backup-${SLURM_JOB_ID}"
|
| 25 |
metre_stage="${metre_repo}/.build-stage-${SLURM_JOB_ID}"
|
|
|
|
| 30 |
test -x "$python"
|
| 31 |
test -d "$sources"
|
| 32 |
test -d "$metre_repo/.git"
|
| 33 |
+
test -s "$stoicheia_conllu"
|
| 34 |
mkdir -p "$stage" "$backup" "$metre_stage" "$metre_backup"
|
| 35 |
|
| 36 |
echo "[$(date --iso-8601=seconds)] rebuilding all configurations from pinned sources"
|
| 37 |
srun --kill-on-bad-exit=1 "$python" -u scripts/build_dataset.py \
|
| 38 |
--sources "$sources" --output "$stage/data" --metadata "$stage/metadata" \
|
| 39 |
+
--metre-output "$metre_stage/data" --metre-metadata "$metre_stage/metadata" \
|
| 40 |
+
--stoicheia-conllu "$stoicheia_conllu"
|
| 41 |
|
| 42 |
echo "[$(date --iso-8601=seconds)] independently validating both staged publications"
|
| 43 |
srun --kill-on-bad-exit=1 "$python" -u scripts/validate_publication.py \
|
slurm/stoicheia_parse_hypotactic.slurm
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
#SBATCH --job-name=sphragis-stoicheia
|
| 3 |
+
#SBATCH --account=naiss2026-3-353-gpu
|
| 4 |
+
#SBATCH --partition=gpu
|
| 5 |
+
#SBATCH --nodes=1
|
| 6 |
+
#SBATCH --ntasks=1
|
| 7 |
+
#SBATCH --cpus-per-task=16
|
| 8 |
+
#SBATCH --gpus=1
|
| 9 |
+
#SBATCH --mem=128G
|
| 10 |
+
#SBATCH --time=12:00:00
|
| 11 |
+
#SBATCH --output=/nobackup/proj/flash/dionysus/personal/cleland/sphragis/.logs/%x-%j.out
|
| 12 |
+
#SBATCH --error=/nobackup/proj/flash/dionysus/personal/cleland/sphragis/.logs/%x-%j.err
|
| 13 |
+
|
| 14 |
+
set -Eeuo pipefail
|
| 15 |
+
trap 'status=$?; echo "[$(date --iso-8601=seconds)] FATAL line=${LINENO} command=${BASH_COMMAND} status=${status}" >&2; exit "$status"' ERR
|
| 16 |
+
source /nobackup/proj/flash/dionysus/personal/cleland/sphragis/slurm/date_logs.sh
|
| 17 |
+
|
| 18 |
+
repo=/nobackup/proj/flash/dionysus/personal/cleland/sphragis
|
| 19 |
+
sources=/nobackup/proj/flash/dionysus/personal/cleland/.sphregis-investigation.VmoHEE
|
| 20 |
+
python=/nobackup/proj/flash/dionysus/personal/cleland/sphragis_models/.venv/bin/python
|
| 21 |
+
output="$repo/.stoicheia-cache/hypotactic_conllu.jsonl"
|
| 22 |
+
export HF_HOME="${SNIC_TMP}/sphragis-stoicheia-hf"
|
| 23 |
+
export PYTHONUNBUFFERED=1
|
| 24 |
+
|
| 25 |
+
cd "$repo"
|
| 26 |
+
echo "[$(date --iso-8601=seconds)] host=$(hostname) job=${SLURM_JOB_ID} starting Stoicheia parsing"
|
| 27 |
+
echo "[$(date --iso-8601=seconds)] gpu=$(nvidia-smi --query-gpu=name,memory.total --format=csv,noheader)"
|
| 28 |
+
test -x "$python"
|
| 29 |
+
mkdir -p "$(dirname "$output")" "$HF_HOME"
|
| 30 |
+
df -h "$SNIC_TMP"
|
| 31 |
+
|
| 32 |
+
if ! "$python" -c 'import torch, transformers, huggingface_hub, safetensors, edlib, pyarrow' 2>/dev/null; then
|
| 33 |
+
echo "[$(date --iso-8601=seconds)] installing pinned Stoicheia inference requirements"
|
| 34 |
+
"$python" -m pip install --disable-pip-version-check \
|
| 35 |
+
-r requirements-build.txt -r requirements-stoicheia.txt
|
| 36 |
+
fi
|
| 37 |
+
"$python" - <<'PY'
|
| 38 |
+
import torch, transformers
|
| 39 |
+
print(f"runtime torch={torch.__version__} transformers={transformers.__version__} cuda={torch.cuda.is_available()}", flush=True)
|
| 40 |
+
assert torch.cuda.is_available()
|
| 41 |
+
PY
|
| 42 |
+
|
| 43 |
+
srun --kill-on-bad-exit=1 "$python" -u scripts/stoicheia_parse_hypotactic.py \
|
| 44 |
+
--hypotactic "$sources/hypotactic" --output "$output" \
|
| 45 |
+
--batch-size 64 --log-every 1024
|
| 46 |
+
|
| 47 |
+
echo "[$(date --iso-8601=seconds)] completed lines=$(wc -l < "$output") bytes=$(stat -c %s "$output")"
|
tests/test_split_stratification.py
CHANGED
|
@@ -160,6 +160,35 @@ def test_metre_chunks_concatenate_every_constituent_syllable() -> None:
|
|
| 160 |
]
|
| 161 |
|
| 162 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 163 |
def test_scansion_is_not_published() -> None:
|
| 164 |
for suffix in (1, 10, 100):
|
| 165 |
for split in SPLITS:
|
|
|
|
| 160 |
]
|
| 161 |
|
| 162 |
|
| 163 |
+
def test_metre_syntax_origin_is_explicit_and_provenance_matches() -> None:
|
| 164 |
+
atomic_origins = set()
|
| 165 |
+
for split in SPLITS:
|
| 166 |
+
rows = pq.read_table(
|
| 167 |
+
config_path(METRE_ROOT, "verse_metre", 1, split),
|
| 168 |
+
columns=["syntax_annotation", "treebank_source", "source_records"],
|
| 169 |
+
).to_pylist()
|
| 170 |
+
for row in rows:
|
| 171 |
+
origin = row["syntax_annotation"]
|
| 172 |
+
atomic_origins.add(origin)
|
| 173 |
+
sources = {record["source"] for record in json.loads(row["source_records"])}
|
| 174 |
+
assert "hypotactic" in sources
|
| 175 |
+
if origin == "predicted":
|
| 176 |
+
assert row["treebank_source"] == "stoicheia_tagger_parser"
|
| 177 |
+
assert "stoicheia_tagger_parser" in sources
|
| 178 |
+
else:
|
| 179 |
+
assert origin == "gold"
|
| 180 |
+
assert "stoicheia_tagger_parser" not in sources
|
| 181 |
+
assert atomic_origins == {"gold", "predicted"}
|
| 182 |
+
|
| 183 |
+
for suffix in (10, 100):
|
| 184 |
+
for split in SPLITS:
|
| 185 |
+
origins = set(pq.read_table(
|
| 186 |
+
config_path(METRE_ROOT, "verse_metre", suffix, split),
|
| 187 |
+
columns=["syntax_annotation"],
|
| 188 |
+
)["syntax_annotation"].to_pylist())
|
| 189 |
+
assert origins <= {"gold", "predicted", "mixed"}
|
| 190 |
+
|
| 191 |
+
|
| 192 |
def test_scansion_is_not_published() -> None:
|
| 193 |
for suffix in (1, 10, 100):
|
| 194 |
for split in SPLITS:
|