File size: 3,683 Bytes
85f00da
4a0d2b0
85f00da
 
 
 
 
1bcc6c0
85f00da
1bcc6c0
85f00da
 
 
 
ecfe7f5
 
 
 
 
 
 
1bcc6c0
ecfe7f5
 
 
 
 
 
 
1bcc6c0
ecfe7f5
 
 
 
 
 
 
 
 
 
24c3b46
 
 
 
 
 
 
 
1bcc6c0
 
24c3b46
 
ecfe7f5
 
 
 
 
 
 
 
 
 
 
4a0d2b0
 
 
 
 
ecfe7f5
 
 
 
 
1bcc6c0
 
 
 
 
ecfe7f5
1bcc6c0
 
 
 
 
 
 
 
 
 
 
 
85f00da
 
 
 
 
 
 
ecfe7f5
 
 
85f00da
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Regenerate all Sphragis task variants from the current atomic datasets."""

from __future__ import annotations

import argparse
import json
import os
from pathlib import Path
import tempfile

import pyarrow as pa
import pyarrow.parquet as pq

try:
    from scripts.dataset_variants import (
        BASE_CONFIGS,
        SPLITS,
        make_dataset_variants,
        variant_schema,
    )
    from scripts.metrical_lines import sanitize_metrical_lines
except ModuleNotFoundError:  # Direct execution from the scripts directory.
    from dataset_variants import (  # type: ignore[no-redef]
        BASE_CONFIGS,
        SPLITS,
        make_dataset_variants,
        variant_schema,
    )
    from metrical_lines import sanitize_metrical_lines


def read_full_configs(data_root: Path) -> tuple[dict[str, list[dict]], dict[str, pa.Schema]]:
    rows_by_config = {}
    schemas = {}
    for base_config in BASE_CONFIGS:
        rows = []
        for split in SPLITS:
            path = data_root / f"{base_config}_1" / f"{split}-00000-of-00001.parquet"
            parquet = pq.ParquetFile(path)
            table = parquet.read(use_threads=False)
            if base_config == "verse_metre" and "scansion" in table.column_names:
                table = table.drop(["scansion"])
            schemas.setdefault(base_config, table.schema)
            assert table.schema == schemas[base_config]
            split_rows = table.to_pylist()
            if base_config == "verse_sentence":
                for row in split_rows:
                    row["metrical_lines"] = sanitize_metrical_lines(
                        row["metrical_lines"]
                    )
            rows.extend(split_rows)
        rows_by_config[base_config] = rows
    return rows_by_config, schemas


def write_variants(
    data_root: Path,
    variants: dict[str, list[dict]],
    schemas: dict[str, pa.Schema],
) -> None:
    for config, rows in variants.items():
        base_config = config.rsplit("_", 1)[0]
        schema = (
            schemas[base_config]
            if config.endswith("_1")
            else variant_schema(schemas[base_config])
        )
        config_root = data_root / config
        config_root.mkdir(parents=True, exist_ok=True)
        for split in SPLITS:
            split_rows = [row for row in rows if row["split"] == split]
            table = pa.Table.from_pylist(split_rows, schema=schema)
            destination = config_root / f"{split}-00000-of-00001.parquet"
            descriptor, temporary_name = tempfile.mkstemp(
                dir=config_root,
                prefix=f".{destination.name}.",
                suffix=".tmp",
            )
            os.close(descriptor)
            temporary = Path(temporary_name)
            try:
                pq.write_table(
                    table,
                    temporary,
                    compression="zstd",
                    compression_level=9,
                )
                temporary.replace(destination)
            finally:
                temporary.unlink(missing_ok=True)


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--data", type=Path, default=Path("data"))
    parser.add_argument("--report", type=Path)
    args = parser.parse_args()
    rows_by_config, schemas = read_full_configs(args.data)
    variants, report = make_dataset_variants(rows_by_config)
    write_variants(args.data, variants, schemas)
    rendered = json.dumps(report, indent=2, ensure_ascii=False, sort_keys=True) + "\n"
    if args.report:
        args.report.write_text(rendered)
    print(rendered, end="")


if __name__ == "__main__":
    main()