"""Deterministic construction of Sphragis chunk-size configurations.""" from __future__ import annotations import hashlib import json import re from collections import Counter, defaultdict from typing import Any import pyarrow as pa try: from scripts.metrical_lines import load_public_metrical_lines from scripts.text_units import encode_text_units, source_text_units except ModuleNotFoundError: # Direct execution from the scripts directory. from metrical_lines import load_public_metrical_lines from text_units import encode_text_units, source_text_units BASE_CONFIGS = ("prose", "verse_sentence", "verse_metre") SPLITS = ("train", "validation", "test") CHUNK_TARGETS = (10, 100) BOTTLENECK_TARGET = max(CHUNK_TARGETS) CHUNKING_SEED = 776 CHUNK_FIELDS = ( pa.field("chunk_size", pa.int64()), pa.field("chunk_target_size", pa.int64()), pa.field("constituent_ids", pa.list_(pa.string())), pa.field("constituent_provenance", pa.string()), pa.field("chunk_work_ids", pa.list_(pa.string())), pa.field("chunk_works", pa.list_(pa.string())), pa.field("chunk_is_mixed_work", pa.bool_()), ) def variant_schema(base_schema: pa.Schema) -> pa.Schema: return pa.schema([*base_schema, *CHUNK_FIELDS], metadata=base_schema.metadata) def _natural_key(value: Any) -> tuple: text = "" if value is None else str(value) return tuple( (0, int(part)) if part.isdigit() else (1, part.casefold()) for part in re.split(r"(\d+)", text) if part ) def actual_order_key(row: dict) -> tuple: """Sort a row in its best available work-internal textual order.""" source_sentence_id = "" try: records = json.loads(row.get("source_records") or "[]") if records: source_sentence_id = records[0].get("source_sentence_id", "") except (json.JSONDecodeError, TypeError): pass return ( _natural_key(row.get("book")), _natural_key(row.get("poem_sequence")), _natural_key(row.get("line_number")), _natural_key(row.get("passage")), _natural_key(source_sentence_id), row["id"], ) def _stable_score(*parts: Any) -> str: payload = "\x1f".join(str(part) for part in parts) return hashlib.sha256(payload.encode("utf-8")).hexdigest() def seeded_discard_ids( base_config: str, rows: list[dict], target: int, split: str, ) -> list[str]: remainder = len(rows) % target ranked = sorted( rows, key=lambda row: _stable_score( CHUNKING_SEED, base_config, target, split, row["author"], row["id"], ), ) return sorted(row["id"] for row in ranked[:remainder]) def eligible_authors(rows: list[dict], threshold: int) -> set[str]: counts = { split: Counter(row["author"] for row in rows if row["split"] == split) for split in ("validation", "test") } authors = set(counts["validation"]) | set(counts["test"]) return { author for author in authors if counts["validation"][author] >= threshold and counts["test"][author] >= threshold } def select_bottleneck_rows( base_config: str, rows: list[dict], ) -> tuple[list[dict], set[str], dict[str, list[str]]]: """Select the atomic corpus shared by every task size for one genre.""" retained_authors = eligible_authors(rows, BOTTLENECK_TARGET) discarded_by_split: dict[str, list[str]] = {"validation": [], "test": []} discarded_ids = { row["id"] for row in rows if row["author"] not in retained_authors } for split in ("validation", "test"): by_author = defaultdict(list) for row in rows: if row["split"] == split and row["author"] in retained_authors: by_author[row["author"]].append(row) for author in sorted(by_author): author_discarded = seeded_discard_ids( base_config, by_author[author], BOTTLENECK_TARGET, split, ) discarded_by_split[split].extend(author_discarded) discarded_ids.update(author_discarded) selected = [row for row in rows if row["id"] not in discarded_ids] return selected, retained_authors, { split: sorted(ids) for split, ids in discarded_by_split.items() } def _ordered_unique(values: list[Any]) -> list[Any]: seen = set() output = [] for value in values: if value not in seen: seen.add(value) output.append(value) return output def _provenance(row: dict) -> dict: keys = ( "id", "work", "work_id", "cts_urn", "passage", "treebank_source", "book", "poem_sequence", "line_number", "hypotactic_file", ) return {key: row.get(key) for key in keys if key in row} def _chunk_metadata(row: dict, target: int) -> dict: row = dict(row) row.update({ "text": encode_text_units(source_text_units(row["text"])), "chunk_size": 1, "chunk_target_size": target, "constituent_ids": [row["id"]], "constituent_provenance": json.dumps( [_provenance(row)], ensure_ascii=False, sort_keys=True, ), "chunk_work_ids": [row["work_id"]], "chunk_works": [row["work"]], "chunk_is_mixed_work": False, }) return row def _merge_json_records(rows: list[dict], field: str) -> str: merged = [] seen = set() for row in rows: for record in json.loads(row[field]): key = json.dumps(record, ensure_ascii=False, sort_keys=True) if key not in seen: seen.add(key) merged.append(record) return json.dumps(merged, ensure_ascii=False, sort_keys=True) def _merge_metrical_lines(rows: list[dict]) -> str: """Deduplicate overlapping lines by separate IDs, never serialized IDs.""" merged = [] seen_ids = set() for row in rows: lines = load_public_metrical_lines(row["metrical_lines"]) line_ids = row["metrical_line_ids"] if len(lines) != len(line_ids): raise ValueError( f"metrical line/id count mismatch in row {row['id']}: " f"{len(lines)} != {len(line_ids)}" ) for line_id, line in zip(line_ids, lines): if line_id not in seen_ids: seen_ids.add(line_id) merged.append(line) return json.dumps(merged, ensure_ascii=False) def _aggregate_chunk(base_config: str, rows: list[dict], target: int, split: str) -> dict: assert len(rows) == target authors = {row["author"] for row in rows} assert len(authors) == 1 work_ids = _ordered_unique([row["work_id"] for row in rows]) works = _ordered_unique([row["work"] for row in rows]) mixed_work = len(work_ids) > 1 constituent_ids = [row["id"] for row in rows] digest = _stable_score(base_config, target, split, *constituent_ids)[:20] chunk = dict(rows[0]) chunk.update({ "id": f"chunk-{base_config}-{target}-{digest}", "work": works[0] if not mixed_work else "Multiple works", "work_id": work_ids[0] if not mixed_work else f"multiple:{digest}", "text": encode_text_units([ unit for row in rows for unit in source_text_units(row["text"]) ]), "conllu": "\n\n".join(row["conllu"].strip() for row in rows) + "\n\n", "cts_urn": rows[0]["cts_urn"] if len({row["cts_urn"] for row in rows}) == 1 else None, "passage": ( rows[0]["passage"] if len({row["passage"] for row in rows}) == 1 else f"{rows[0]['passage']}–{rows[-1]['passage']}" if not mixed_work else None ), "treebank_source": ( rows[0]["treebank_source"] if len({row["treebank_source"] for row in rows}) == 1 else "multiple" ), "source_records": _merge_json_records(rows, "source_records"), "licenses": sorted({license_name for row in rows for license_name in row["licenses"]}), "dedup_key": hashlib.sha256("\x1f".join(constituent_ids).encode("utf-8")).hexdigest(), "split": split, "chunk_size": target, "chunk_target_size": target, "constituent_ids": constituent_ids, "constituent_provenance": json.dumps( [_provenance(row) for row in rows], ensure_ascii=False, sort_keys=True, ), "chunk_work_ids": work_ids, "chunk_works": works, "chunk_is_mixed_work": mixed_work, }) if base_config == "verse_sentence": chunk.update({ "alignment_component_id": None, "component_sentence_index": None, "metre": [metre for row in rows for metre in row["metre"]], "metrical_line_ids": _ordered_unique([ line_id for row in rows for line_id in row["metrical_line_ids"] ]), "metrical_lines": _merge_metrical_lines(rows), }) elif base_config == "verse_metre": chunk.update({ "parent_sentence_ids": _ordered_unique([ sentence_id for row in rows for sentence_id in row["parent_sentence_ids"] ]), "alignment_component_id": None, "component_line_index": None, "book": rows[0]["book"] if len({row["book"] for row in rows}) == 1 else None, "poem_sequence": None, "line_number": ( f"{rows[0]['line_number']}–{rows[-1]['line_number']}" if not mixed_work else None ), "metre": "\n".join(row["metre"] for row in rows), "syllables": json.dumps( [ syllable for row in rows for syllable in json.loads(row["syllables"]) ], ensure_ascii=False, ), "hypotactic_file": ( rows[0]["hypotactic_file"] if len({row["hypotactic_file"] for row in rows}) == 1 else None ), }) return chunk def chunk_author_rows( base_config: str, rows: list[dict], target: int, split: str, ) -> tuple[list[dict], list[str]]: """Discard the seeded remainder and maximize single-work chunks.""" assert split in {"validation", "test"} discarded_ids = seeded_discard_ids(base_config, rows, target, split) discarded = set(discarded_ids) by_work = defaultdict(list) for row in rows: if row["id"] not in discarded: by_work[row["work_id"]].append(row) chunks = [] tails = [] for work_key in sorted(by_work, key=_natural_key): ordered = sorted(by_work[work_key], key=actual_order_key) full_length = len(ordered) - (len(ordered) % target) for start in range(0, full_length, target): chunks.append(_aggregate_chunk(base_config, ordered[start:start + target], target, split)) tails.extend(ordered[full_length:]) assert len(tails) % target == 0 for start in range(0, len(tails), target): chunks.append(_aggregate_chunk(base_config, tails[start:start + target], target, split)) return chunks, discarded_ids def make_dataset_variants( rows_by_base_config: dict[str, list[dict]], ) -> tuple[dict[str, list[dict]], dict]: variants = {} report = {} for base_config, rows in rows_by_base_config.items(): shared_rows, retained_authors, bottleneck_discarded = select_bottleneck_rows( base_config, rows, ) variants[f"{base_config}_1"] = [ { **row, "text": encode_text_units(source_text_units(row["text"])), } for row in shared_rows ] report[f"{base_config}_1"] = { "authors": len(retained_authors), "retained_authors": sorted(retained_authors), "rows": dict(Counter(row["split"] for row in shared_rows)), "row_unit": "line" if base_config == "verse_metre" else "sentence", "shared_source_selection_target": BOTTLENECK_TARGET, "discarded_source_row_ids": bottleneck_discarded, } for target in CHUNK_TARGETS: config = f"{base_config}_{target}" variant_rows = [ _chunk_metadata(row, target) for row in shared_rows if row["split"] == "train" ] for split in ("validation", "test"): split_chunks = [] by_author = defaultdict(list) for row in shared_rows: if row["split"] == split: by_author[row["author"]].append(row) for author in sorted(by_author): chunks, author_discarded = chunk_author_rows( base_config, by_author[author], target, split, ) assert not author_discarded split_chunks.extend(chunks) variant_rows.extend(split_chunks) variants[config] = variant_rows split_rows = Counter(row["split"] for row in variant_rows) split_source_rows = Counter() mixed_work_chunks = Counter() for row in variant_rows: split_source_rows[row["split"]] += row["chunk_size"] if row["chunk_is_mixed_work"]: mixed_work_chunks[row["split"]] += 1 report[config] = { "authors": len(retained_authors), "minimum_validation_and_test_source_rows_per_author": BOTTLENECK_TARGET, "retained_authors": sorted(retained_authors), "shared_source_selection_target": BOTTLENECK_TARGET, "train_row_unit": "line" if base_config == "verse_metre" else "sentence", "evaluation_row_unit": f"{target}-" + ( "line chunk" if base_config == "verse_metre" else "sentence chunk" ), "rows": dict(split_rows), "represented_source_rows": dict(split_source_rows), "discarded_source_row_ids": bottleneck_discarded, "discarded_source_rows": { split: len(ids) for split, ids in bottleneck_discarded.items() }, "mixed_work_chunks": dict(mixed_work_chunks), "chunking_seed": CHUNKING_SEED, } return variants, report