#!/usr/bin/env python3 """Parse reconstructed Hypotactic sentences and crop their trees to verse lines.""" from __future__ import annotations import argparse from collections import defaultdict import json import os from pathlib import Path import re import sys import time import unicodedata import torch from huggingface_hub import snapshot_download from transformers import AutoModel try: from scripts.build_dataset import ( curated_hypotactic_line, crop_conllu_to_normalized_span, hypotactic_line_key, load_hypotactic, normalize, ) except ModuleNotFoundError: from build_dataset import ( curated_hypotactic_line, crop_conllu_to_normalized_span, hypotactic_line_key, load_hypotactic, normalize, ) MODEL_ID = "Ericu950/Stoicheia-tagger-parser" MODEL_REVISION = "cd8ae1658c364874c3b6f4df37bd1d46313e3cea" SENTENCE_FINAL = re.compile(r"[.!?;\u037e][\]\)}\u00bb\u2019\u201d\"']*$") MAX_WORDS = 350 MAX_CHARS = 1900 def retained_line(stem: str, line: dict) -> dict | None: curated, reason = curated_hypotactic_line(stem, line) if reason: return None return { "key": list(hypotactic_line_key(line)), "stem": stem, "line_sequence": int(line["line_sequence"]), "poem_sequence": line["poem_sequence"], "book": line["book"], **curated, } def _capped_sentence(entries: list[dict]) -> list[tuple[list[dict], bool]]: """Split an overlong punctuation sentence only at metrical-line boundaries.""" chunks = [] start = 0 while start < len(entries): words = chars = 0 end = start last_line_boundary = None while end < len(entries): token = entries[end]["token"] next_words = words + 1 next_chars = chars + len(token) if next_words > MAX_WORDS or next_chars > MAX_CHARS: break words, chars = next_words, next_chars end += 1 if end == len(entries) or entries[end]["key"] != entries[end - 1]["key"]: last_line_boundary = end if end == len(entries): chunks.append((entries[start:end], start > 0)) break if last_line_boundary is None or last_line_boundary <= start: raise ValueError("one metrical line exceeds Stoicheia's safe context window") chunks.append((entries[start:last_line_boundary], True)) start = last_line_boundary return chunks def reconstruct_sentences(retained: list[dict]) -> list[dict]: """Create punctuation-delimited sentences across consecutive metrical lines.""" sentences = [] current = [] previous_group = None previous_sequence = None def finish() -> None: nonlocal current if not current: return if not any(normalize(entry["token"]) for entry in current): # Standalone editorial punctuation may follow a sentence-final word. # Stoicheia intentionally emits no word row for such a segment. current = [] return for entries, forced in _capped_sentence(current): sentence_number = len(sentences) + 1 spans = [] cursor = 0 for entry in entries: length = len(normalize(entry["token"])) if not length: # Editorial punctuation contributes no normalized text and # therefore cannot define a non-empty line crop. continue if spans and spans[-1]["key"] == entry["key"]: spans[-1]["end"] += length else: spans.append({ "key": entry["key"], "start": cursor, "end": cursor + length, }) cursor += length if not cursor: raise ValueError("reconstructed sentence has no Greek token content") sentences.append({ "sentence_id": f"hypotactic-context-{sentence_number:06d}", "tokens": [entry["token"] for entry in entries], "text": " ".join(entry["token"] for entry in entries), "spans": spans, "line_count": len({tuple(span["key"]) for span in spans}), "forced_context_split": forced, }) current = [] for line in retained: group = (line["stem"], line["poem_sequence"], line["book"]) if ( previous_group is not None and (group != previous_group or line["line_sequence"] != previous_sequence + 1) ): finish() for token in line["tokens"]: current.append({"key": line["key"], "token": token}) if SENTENCE_FINAL.search(token): finish() previous_group = group previous_sequence = line["line_sequence"] finish() return sentences def repair_tree(words: list[dict]) -> list[dict]: """Make the greedy biaffine decode a single rooted, acyclic UD tree.""" if not words: raise ValueError("Stoicheia decoded no Greek tokens") n = len(words) original = [(int(word.get("head") or 0), word.get("deprel")) for word in words] heads = [int(word.get("head") or 0) for word in words] roots = [ index for index, (word, head) in enumerate(zip(words, heads), 1) if head == 0 and word["upos"] != "PUNCT" ] primary = roots[0] if roots else next( (index for index, word in enumerate(words, 1) if word["upos"] != "PUNCT"), 1, ) for index, word in enumerate(words, 1): head = heads[index - 1] if index == primary: heads[index - 1] = 0 word["deprel"] = "root" elif head < 0 or head > n or head in {0, index}: heads[index - 1] = primary word["deprel"] = "punct" if word["upos"] == "PUNCT" else "dep" elif word.get("deprel") == "root": word["deprel"] = "dep" changed = True while changed: changed = False for token_id in range(1, n + 1): trail = [] cursor = token_id while cursor: if cursor in trail: cycle = trail[trail.index(cursor):] break_id = min(cycle) heads[break_id - 1] = 0 if break_id == primary else primary words[break_id - 1]["deprel"] = ( "root" if break_id == primary else "dep" ) changed = True break trail.append(cursor) cursor = heads[cursor - 1] if changed: break for word, head, (old_head, old_deprel) in zip(words, heads, original): word["head"] = head word["head_repair"] = head != old_head or word.get("deprel") != old_deprel return words def restore_alphabetic_non_greek_tokens( tokens: list[str], words: list[dict], ) -> list[dict]: """Restore alphabetic tokens the character model intentionally omits.""" old_to_new = {} merged = [] decoded_index = 0 for token in tokens: has_greek = any("GREEK" in unicodedata.name(char, "") for char in token) if has_greek: if decoded_index >= len(words) or words[decoded_index]["form"] != token: raise ValueError("Stoicheia form order differs from Hypotactic tokens") decoded_index += 1 old_to_new[decoded_index] = len(merged) + 1 merged.append(dict(words[decoded_index - 1])) elif normalize(token): merged.append({ "form": token, "lemma": token, "upos": "X", "xpos": "x--------", "feats": {}, "head": 0, "deprel": "dep", "_restored": True, }) if decoded_index != len(words): raise ValueError("Stoicheia returned unexpected extra forms") for word in merged: if word.pop("_restored", False): continue if word.get("head"): word["head"] = old_to_new[word["head"]] return merged def encode_conllu(text: str, tokens: list[str], words: list[dict]) -> str: words = restore_alphabetic_non_greek_tokens(tokens, words) words = repair_tree(words) lines = [f"# text = {text}"] for index, word in enumerate(words, 1): feats = word.get("feats") or {} feat_text = "|".join(f"{key}={feats[key]}" for key in sorted(feats)) or "_" lines.append("\t".join([ str(index), word["form"], word.get("lemma") or "_", word.get("upos") or "X", word.get("xpos") or "_", feat_text, str(word["head"]), word.get("deprel") or "dep", "_", "HeadRepair=Yes" if word["head_repair"] else "_", ])) conllu = "\n".join(lines) + "\n\n" forms = "".join(word["form"] for word in words) if normalize(forms) != normalize(text): raise ValueError("Stoicheia forms do not cover the Hypotactic line") return conllu def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--hypotactic", type=Path, required=True) parser.add_argument("--output", type=Path, required=True) parser.add_argument("--batch-size", type=int, default=64) parser.add_argument("--log-every", type=int, default=1024) args = parser.parse_args() all_lines = load_hypotactic(args.hypotactic, all_files=True) retained = [ row for stem, lines in sorted(all_lines.items()) for line in lines if (row := retained_line(stem, line)) is not None ] keys = [tuple(row["key"]) for row in retained] if len(keys) != len(set(keys)): raise ValueError("Hypotactic line keys are not unique") sentences = reconstruct_sentences(retained) args.output.parent.mkdir(parents=True, exist_ok=True) print( f"inventory retained_lines={len(retained)} reconstructed_sentences={len(sentences)} " f"multiline_sentences={sum(row['line_count'] > 1 for row in sentences)} " f"forced_context_splits={sum(row['forced_context_split'] for row in sentences)} " f"model={MODEL_ID}@{MODEL_REVISION}", flush=True, ) local = snapshot_download( MODEL_ID, revision=MODEL_REVISION, allow_patterns=["*.json", "*.txt", "*.py", "*.model", "*.safetensors"], ) sys.path.insert(0, local) from processing_char_bert_joint import CharBertJointProcessor device = torch.device("cuda") model = AutoModel.from_pretrained( local, trust_remote_code=True, dtype=torch.bfloat16, ).to(device).eval() processor = CharBertJointProcessor.from_pretrained(local) print( f"loaded model device={device} dtype={next(model.parameters()).dtype} " f"batch_size={args.batch_size}", flush=True, ) started = time.monotonic() fragments = defaultdict(list) temporary = args.output.with_suffix(args.output.suffix + ".incomplete") with temporary.open("w", encoding="utf-8", buffering=1) as handle: for start in range(0, len(sentences), args.batch_size): items = sentences[start:start + args.batch_size] batch = processor([item["tokens"] for item in items]) model_batch = { key: value.to(device, non_blocking=True) for key, value in batch.items() if not key.startswith("_") } with torch.inference_mode(): output = model(**model_batch) decoded = processor.decode(output, batch, ud=True) if len(decoded) != len(items): raise RuntimeError("Stoicheia returned the wrong batch cardinality") for item, words in zip(items, decoded): sentence_conllu = encode_conllu(item["text"], item["tokens"], words) for span in item["spans"]: fragments[tuple(span["key"])].append({ "conllu": crop_conllu_to_normalized_span( sentence_conllu, span["start"], span["end"], ), "sentence_id": item["sentence_id"], "line_count": item["line_count"], "forced_context_split": item["forced_context_split"], }) done = start + len(items) if done == len(sentences) or done % args.log_every < args.batch_size: elapsed = time.monotonic() - started rate = done / elapsed if elapsed else 0 print( f"progress sentences={done}/{len(sentences)} " f"rate={rate:.1f}_sentences_s elapsed={elapsed:.1f}s", flush=True, ) if set(fragments) != set(keys): raise RuntimeError( f"sentence cropping did not cover every retained line: " f"missing={len(set(keys) - set(fragments))} " f"extra={len(set(fragments) - set(keys))}" ) retained_by_key = {tuple(row["key"]): row for row in retained} for key in keys: item = retained_by_key[key] pieces = fragments[key] conllu = "".join(piece["conllu"] for piece in pieces) result = { **{name: item[name] for name in ("key", "author", "work", "work_id", "text")}, "conllu": conllu, "context_sentence_ids": [piece["sentence_id"] for piece in pieces], "context_sentence_line_counts": [piece["line_count"] for piece in pieces], "context_forced_splits": [piece["forced_context_split"] for piece in pieces], "context_parsing": "sentence_then_crop_v1", "model": MODEL_ID, "model_revision": MODEL_REVISION, } forms = "".join( columns[1] for line in conllu.splitlines() if not line.startswith("#") and line for columns in [line.split("\t")] if len(columns) == 10 and columns[0].isdigit() ) if normalize(forms) != normalize(item["text"]): raise ValueError(f"cropped sentence trees do not cover line {key}") handle.write(json.dumps(result, ensure_ascii=False, sort_keys=True) + "\n") handle.flush() os.fsync(handle.fileno()) os.replace(temporary, args.output) print( f"completed lines={len(keys)} sentence_fragments={sum(map(len, fragments.values()))} " f"output={args.output}", flush=True, ) if __name__ == "__main__": main()