File size: 3,843 Bytes
aaee816
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Writing a corpus out as selectable Hugging Face subsets.

Both corpora expose the same subset names: ``all`` plus one per translation direction,
written ``<target>-<pivot>``. A name therefore identifies the same language pair in the
evaluation corpus and in the baseline, so the test split and the training data for one
direction can be loaded without any cross-referencing. The baseline adds subsets by how the
data was produced, because the raw totals hide that distinction entirely.

Each subset gets one parquet file per split it contains, under
``subsets/<name>/<split>.parquet``, which is the layout the Hub's ``configs`` front matter
addresses directly.
"""

from __future__ import annotations

from pathlib import Path


def write_subsets(output: Path, subsets: dict, as_table, *, split=None,
                  split_of=None, human_types=()) -> dict:
    """Write each subset and return its manifest entry.

    ``split`` names a single split for every record; ``split_of`` is a callable returning the
    split for one record, used where a subset holds more than one. Empty subsets are skipped
    rather than published, so a reader never loads a config with no rows.
    """
    import pyarrow.parquet as pq

    meta = {}
    for name, items in subsets.items():
        if not items:
            continue
        grouped: dict[str, list] = {}
        for record in items:
            key = split if split is not None else split_of(record)
            grouped.setdefault(key, []).append(record)
        base = output / "subsets" / name
        base.mkdir(parents=True, exist_ok=True)
        splits, total_bytes = {}, 0
        for part, rows in sorted(grouped.items()):
            path = base / f"{part}.parquet"
            pq.write_table(as_table(rows), path, compression="zstd")
            splits[part] = {"records": len(rows), "path": f"subsets/{name}/{part}.parquet"}
            total_bytes += path.stat().st_size
        languages = sorted({r["tl"] for r in items})
        pivots = sorted({r["sl"] for r in items})
        sources = sorted({r.get("source") for r in items if r.get("source")})
        corpora = sorted({r.get("corpus") for r in items if r.get("corpus")})
        entry = {
            "records": len(items),
            "splits": splits,
            "languages": languages,
            "pivots": pivots,
            "sources": sources[:25],
            "source_count": len(sources),
            "bytes": total_bytes,
            # True for the "<source>-<language>" subsets: one body of data, one language.
            "is_source_subset": len(languages) == 1 and len(corpora or sources) == 1,
        }
        if corpora:
            entry["corpora"] = corpora[:25]
        types = sorted({r.get("corpus_type") for r in items if r.get("corpus_type")})
        if types:
            entry["corpus_types"] = types
            entry["is_human"] = bool(human_types) and all(t in human_types for t in types)
        meta[name] = entry
    return meta

# Upstream names differ in case and punctuation, and the same body of data can arrive under
# two labels: the evaluation corpus reads the Tatoeba Challenge's held-out test split while
# the baseline reads OPUS's Tatoeba corpus. Both are Tatoeba, so both slug to "tatoeba" and
# a subset name then means the same source in either dataset.
SOURCE_ALIASES = {
    "tatoeba_challenge": "tatoeba",
    "tatoeba-challenge": "tatoeba",
}


def source_slug(name: str) -> str:
    """A Hub-safe subset component for a source or corpus name."""
    import re

    slug = re.sub(r"[^a-z0-9]+", "_", (name or "").lower()).strip("_")
    return SOURCE_ALIASES.get(slug, slug)


def subset_name(source: str, language: str) -> str:
    """``<source>-<language>``: where the data came from, and which language it is for."""
    return f"{source_slug(source)}-{language}"