Datasets:
Tasks:
Text Classification
Formats:
parquet
Languages:
Ancient Greek (to 1453)
Size:
100K - 1M
License:
File size: 14,451 Bytes
ecfe7f5 1bcc6c0 e1e2e3d 1bcc6c0 e1e2e3d 1bcc6c0 ecfe7f5 4a0d2b0 ecfe7f5 4a0d2b0 ecfe7f5 e1e2e3d ecfe7f5 1bcc6c0 ecfe7f5 e1e2e3d ac04b84 ecfe7f5 1bcc6c0 ecfe7f5 24c3b46 ecfe7f5 4a0d2b0 e1e2e3d ecfe7f5 4a0d2b0 ecfe7f5 4a0d2b0 ecfe7f5 4a0d2b0 ecfe7f5 4a0d2b0 ecfe7f5 4a0d2b0 ecfe7f5 4a0d2b0 ecfe7f5 4a0d2b0 ecfe7f5 4a0d2b0 ecfe7f5 4a0d2b0 ecfe7f5 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 | """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
|