sphragis / scripts /build_sqlite_mirror.py
Urdatorn's picture
Rebuild Sphragis from the complete treebank sentence pool
733d9e5
Raw
History Blame Contribute Delete
8.94 kB
#!/usr/bin/env python3
"""Build and validate a human-inspection SQLite mirror of Sphragis."""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import sqlite3
from pathlib import Path
from typing import Any
import pyarrow as pa
import pyarrow.parquet as pq
SPLITS = ("train", "validation", "test")
CONFIGS = tuple(f"sentence_{suffix}" for suffix in ("1", "10", "100"))
INDEX_COLUMN = "_split_row_index"
def quote(identifier: str) -> str:
return '"' + identifier.replace('"', '""') + '"'
def sqlite_type(field: pa.Field) -> str:
datatype = field.type
if pa.types.is_boolean(datatype) or pa.types.is_integer(datatype):
return "INTEGER"
if pa.types.is_floating(datatype):
return "REAL"
if pa.types.is_binary(datatype) or pa.types.is_large_binary(datatype):
return "BLOB"
return "TEXT"
def sqlite_value(value: Any) -> Any:
if isinstance(value, (list, dict)):
return json.dumps(
value, ensure_ascii=False, sort_keys=True, separators=(",", ":"),
)
if isinstance(value, bool):
return int(value)
return value
def digest_rows(rows: list[dict[str, Any]], columns: list[str]) -> str:
digest = hashlib.sha256()
for row in rows:
encoded = json.dumps(
[sqlite_value(row[column]) for column in columns],
ensure_ascii=False,
separators=(",", ":"),
)
digest.update(encoded.encode("utf-8"))
digest.update(b"\n")
return digest.hexdigest()
def parquet_path(data_root: Path, config: str, split: str) -> Path:
return data_root / config / f"{split}-00000-of-00001.parquet"
def build(data_root: Path, destination: Path) -> None:
destination.parent.mkdir(parents=True, exist_ok=True)
temporary = destination.with_name(f".{destination.name}.tmp-{os.getpid()}")
temporary.unlink(missing_ok=True)
connection = sqlite3.connect(temporary)
try:
connection.execute("PRAGMA page_size = 32768")
connection.execute("PRAGMA journal_mode = OFF")
connection.execute("PRAGMA synchronous = OFF")
connection.execute("PRAGMA temp_store = MEMORY")
connection.execute("PRAGMA application_id = 0x53504852")
connection.execute("PRAGMA user_version = 1")
connection.execute(
"CREATE TABLE _mirror_manifest ("
"config TEXT NOT NULL, split TEXT NOT NULL, rows INTEGER NOT NULL, "
"columns_json TEXT NOT NULL, content_sha256 TEXT NOT NULL, "
"PRIMARY KEY (config, split)) WITHOUT ROWID"
)
for config in CONFIGS:
first = pq.ParquetFile(parquet_path(data_root, config, SPLITS[0]))
schema = first.schema_arrow
columns = schema.names
if INDEX_COLUMN in columns:
raise ValueError(f"reserved column already exists: {INDEX_COLUMN}")
definitions = [f"{quote(INDEX_COLUMN)} INTEGER NOT NULL"] + [
f"{quote(field.name)} {sqlite_type(field)}"
for field in schema
]
connection.execute(
f"CREATE TABLE {quote(config)} ({', '.join(definitions)}, "
f"PRIMARY KEY ({quote('split')}, {quote(INDEX_COLUMN)})) WITHOUT ROWID"
)
placeholders = ",".join("?" for _ in range(len(columns) + 1))
insert = f"INSERT INTO {quote(config)} VALUES ({placeholders})"
for split in SPLITS:
path = parquet_path(data_root, config, split)
parquet = pq.ParquetFile(path)
if parquet.schema_arrow != schema:
raise ValueError(f"schema mismatch: {path}")
split_rows: list[dict[str, Any]] = []
next_index = 0
for batch in parquet.iter_batches(batch_size=512, use_threads=False):
rows = batch.to_pylist()
connection.executemany(
insert,
[
(next_index + offset, *(
sqlite_value(row[column]) for column in columns
))
for offset, row in enumerate(rows)
],
)
next_index += len(rows)
split_rows.extend(rows)
connection.execute(
"INSERT INTO _mirror_manifest VALUES (?, ?, ?, ?, ?)",
(
config,
split,
next_index,
json.dumps(columns, separators=(",", ":")),
digest_rows(split_rows, columns),
),
)
print(f"mirrored {config}/{split}: {next_index} rows", flush=True)
connection.execute(
f"CREATE INDEX {quote(config + '_author_split')} "
f"ON {quote(config)} ({quote('author')}, {quote('split')})"
)
connection.commit()
connection.execute("ANALYZE")
connection.commit()
integrity = connection.execute("PRAGMA integrity_check").fetchone()[0]
if integrity != "ok":
raise RuntimeError(f"SQLite integrity check failed: {integrity}")
except BaseException:
connection.close()
temporary.unlink(missing_ok=True)
raise
connection.close()
temporary.replace(destination)
def validate(data_root: Path, database: Path) -> None:
connection = sqlite3.connect(f"file:{database}?mode=ro", uri=True)
try:
integrity = connection.execute("PRAGMA integrity_check").fetchone()[0]
if integrity != "ok":
raise RuntimeError(f"SQLite integrity check failed: {integrity}")
tables = {
row[0] for row in connection.execute(
"SELECT name FROM sqlite_schema "
"WHERE type = 'table' AND name NOT LIKE 'sqlite_%'"
)
}
expected_tables = {*CONFIGS, "_mirror_manifest"}
if tables != expected_tables:
raise AssertionError(f"unexpected SQLite tables: {tables ^ expected_tables}")
for config in CONFIGS:
for split in SPLITS:
path = parquet_path(data_root, config, split)
table = pq.read_table(path, use_threads=False)
columns = table.column_names
rows = table.to_pylist()
expected_digest = digest_rows(rows, columns)
manifest = connection.execute(
"SELECT rows, columns_json, content_sha256 "
"FROM _mirror_manifest WHERE config = ? AND split = ?",
(config, split),
).fetchone()
if manifest != (
len(rows),
json.dumps(columns, separators=(",", ":")),
expected_digest,
):
raise AssertionError(f"manifest mismatch: {config}/{split}")
selected = connection.execute(
f"SELECT {', '.join(quote(column) for column in columns)} "
f"FROM {quote(config)} WHERE split = ? "
f"ORDER BY {quote(INDEX_COLUMN)}",
(split,),
)
database_digest = hashlib.sha256()
database_rows = 0
for result in selected:
encoded = json.dumps(
list(result), ensure_ascii=False, separators=(",", ":"),
)
database_digest.update(encoded.encode("utf-8"))
database_digest.update(b"\n")
database_rows += 1
if database_rows != len(rows) or database_digest.hexdigest() != expected_digest:
raise AssertionError(f"content mismatch: {config}/{split}")
print(f"validated {config}/{split}: {database_rows} rows", flush=True)
finally:
connection.close()
def main() -> None:
global CONFIGS
parser = argparse.ArgumentParser()
parser.add_argument("--data", type=Path, default=Path("data"))
parser.add_argument(
"--output", type=Path, default=Path("inspection/sphragis.sqlite"),
)
parser.add_argument(
"--publication", choices=("sentence", "metre"), default="sentence",
)
parser.add_argument("--check", action="store_true")
args = parser.parse_args()
base = "sentence" if args.publication == "sentence" else "verse_metre"
CONFIGS = tuple(f"{base}_{suffix}" for suffix in ("1", "10", "100"))
if not args.check:
build(args.data, args.output)
validate(args.data, args.output)
print(f"SQLite mirror ready: {args.output} ({args.output.stat().st_size} bytes)")
if __name__ == "__main__":
main()