File size: 11,123 Bytes
19c22ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Training data for the EveryVoice (FastSpeech2 + HiFi-GAN) systems of the listening test, in the layout the EveryVoice wizard
(`everyvoice new-project`) reads: one folder of wavs and a pipe-separated filelist with a header. One single-speaker studio corpus
per language that has no Open Bible checkpoint:

    Japanese    JSUT 1.1 (data/jsut_ver1.1.zip, unzipped)           1 female, 48 kHz,   7,696 utts, 10.3 h  research / non-commercial
    Korean      KSS (Bingsu/KSS_Dataset)                            1 female, 44.1 kHz, 12,854 utts, 12.9 h  CC BY-NC-SA 4.0
    Indonesian  INDspeech_NEWS_TTS, config indspeech_news_tts_120_MOS_source, train split only (davidguzmanr/INDspeech_NEWS_TTS, private)
                                                                    1 female, 16 kHz,   1,972 utts, 1.9 h   CC BY-NC-SA 4.0

Per language this writes data/EveryVoice/<Language>/ (git-ignored; none of these corpora may be redistributed):
    wavs/<basename>.wav   mono 16-bit PCM at the corpus' own sample rate (EveryVoice resamples in `everyvoice preprocess`)
    metadata.psv          basename|text|speaker|language, the training list to give the wizard
    transcripts.csv       every utterance: source text, training text, duration, kept / why not, for review

Text given to EveryVoice (character input, as in the Open Bible EveryVoice models):
    Japanese    katakana as pronounced, from vits/kana.py (pyopenjtalk), the same front end as the Japanese VITS. JSUT has 2,723
                distinct kanji/kana, half of them seen < 10 times, and kanji readings depend on the word; katakana leaves ~80 symbols.
    Korean      KSS `expanded_script` (numbers and Latin acronyms already spelled out in Hangul) decomposed into conjoining jamo
                (Unicode NFD): 1,226 distinct syllables, 488 seen < 10 times -> ~67 jamo. The dataset's own `decomposed_script` is
                not used (22 rows are broken, e.g. 의미ᅡᆸ니까). Do NOT pick "NFC Normalization" in the wizard: it recomposes the
                jamo into syllables. EveryVoice tokenises per code point, so the jamo stay separate tokens.
    Indonesian  the transcript as is (Latin letters and . , ? ! -; no digits); case is kept, as in the pilot Open Bible models.
The wizard's symbol list groups NFD jamo back into syllables (grapheme clusters): replace KSS_characters with the jamo (README).
Utterances are dropped when longer than --max-s (15 s, the cap of the Open Bible EveryVoice runs), when the front end cannot read
a character (Japanese), or when the sentence is one of the listening-test sentences in audios/<Language>/ground-truth/metadata.csv
(none are, checked here on every run). INDspeech's `test` split is the 40-sentence MOS list the Indonesian ground truth is drawn
from, so only `train` is used; the ZR_ZR configs (ZeroSpeech split) contain 38 of those 40 sentences in train and are not used.

Env: EveryVoice-env (needs pyopenjtalk 0.4.1 for Japanese). Run from anywhere:
    python everyvoice-tts/prepare_data.py --language Japanese     # or Korean, Indonesian; several at once is fine
"""
import argparse, collections, glob, io, os, re, shutil, sys, unicodedata
from pathlib import Path
import numpy as np, pandas as pd, pyarrow.parquet as pq, soundfile as sf

REPO = Path(__file__).resolve().parents[1]
DATA = REPO / "data"
CORPORA = {   # speaker id and language id go into the filelist; sample_rate is what the wizard asks for
    "Japanese": dict(speaker="jsut", language="jpn", sample_rate=48000),
    "Korean": dict(speaker="kss", language="kor", sample_rate=44100),
    "Indonesian": dict(speaker="indspeech", language="ind", sample_rate=16000),
}
KSS_REPO, INDSPEECH_REPO, INDSPEECH_CONFIG = "Bingsu/KSS_Dataset", "davidguzmanr/INDspeech_NEWS_TTS", "indspeech_news_tts_120_MOS_source"


def sentence_key(text):
    """Comparison key for the overlap check: NFKC, casefolded, letters and digits only."""
    return "".join(ch for ch in unicodedata.normalize("NFKC", str(text)).casefold() if unicodedata.category(ch)[0] in "LN")


# ---- corpus readers: yield dict(basename, source_text, text, why, write) where write(dst) puts a mono 16-bit wav at dst

def link_or_copy(src):
    def write(dst):
        try: os.link(src, dst)
        except OSError: shutil.copy2(src, dst)
    return write


def from_bytes(data, sample_rate):
    """Write wav bytes from a parquet row as mono 16-bit PCM; bytes that already are that format are written unchanged."""
    def write(dst):
        info = sf.info(io.BytesIO(data))
        assert info.samplerate == sample_rate, f"{dst}: {info.samplerate} Hz, expected {sample_rate}"
        if info.channels == 1 and info.format == "WAV" and info.subtype == "PCM_16":
            Path(dst).write_bytes(data); return
        y, sr = sf.read(io.BytesIO(data), dtype="float32", always_2d=True)
        sf.write(dst, y.mean(axis=1), sr, subtype="PCM_16")                   # KSS has one stereo file (channels differ): downmix
    return write


def read_jsut():
    sys.path.insert(0, str(REPO / "vits")); from kana import convert   # noqa: E402  (same front end as the Japanese VITS)
    root = DATA / "jsut_ver1.1"
    files = sorted(root.glob("*/transcript_utf8.txt"))
    if not files: sys.exit(f"no transcripts under {root}: unzip data/jsut_ver1.1.zip into data/ first")
    for f in files:
        for line in f.read_text(encoding="utf-8").splitlines():
            if ":" not in line: continue
            uid, text = line.split(":", 1); wav = f.parent / "wav" / f"{uid}.wav"
            kana, unconverted = convert(text)
            why = [f"unconverted: {''.join(unconverted)}"] if unconverted else []
            why += ["no kana"] if not any(unicodedata.category(c)[0] == "L" for c in kana) else []
            yield dict(basename=uid, subset=f.parent.name, source_text=text, text=kana, duration_s=sf.info(wav).duration,
                       why=why, write=link_or_copy(wav))


def parquet_rows(files, columns):
    for f in files:
        for batch in pq.ParquetFile(f).iter_batches(batch_size=256, columns=columns):
            yield from batch.to_pylist()


def read_kss():
    files = sorted(glob.glob(str(DATA / "KSS" / "data" / "train-*.parquet")))
    if not files:
        from huggingface_hub import snapshot_download
        snapshot_download(KSS_REPO, repo_type="dataset", local_dir=DATA / "KSS")
        files = sorted(glob.glob(str(DATA / "KSS" / "data" / "train-*.parquet")))
    for i, r in enumerate(parquet_rows(files, ["audio", "original_script", "expanded_script"])):
        data = r["audio"]["bytes"]; jamo = unicodedata.normalize("NFD", " ".join(r["expanded_script"].split()))
        bad = sorted({c for c in jamo if unicodedata.category(c)[0] in "LN" and not "ᄀ" <= c <= "ᇿ"})
        yield dict(basename=f"KSS_{i:05d}", subset="", source_text=r["original_script"], text=jamo, duration_s=sf.info(io.BytesIO(data)).duration,
                   why=[f"non-jamo letters: {''.join(bad)}"] if bad else [], write=from_bytes(data, CORPORA["Korean"]["sample_rate"]))


def read_indspeech():
    path = DATA / "INDspeech" / INDSPEECH_CONFIG / "train-00000-of-00001.parquet"
    if not path.exists():
        from huggingface_hub import snapshot_download   # private repo: needs the token in $HF_HOME/token (hf auth login)
        snapshot_download(INDSPEECH_REPO, repo_type="dataset", local_dir=DATA / "INDspeech", allow_patterns=[f"{INDSPEECH_CONFIG}/*", "README.md"])
    for r in parquet_rows([path], ["id", "audio", "text"]):
        data = r["audio"]["bytes"]
        yield dict(basename=r["id"], subset="train", source_text=r["text"], text=" ".join(r["text"].split()), duration_s=sf.info(io.BytesIO(data)).duration,
                   why=[], write=from_bytes(data, CORPORA["Indonesian"]["sample_rate"]))


READERS = {"Japanese": read_jsut, "Korean": read_kss, "Indonesian": read_indspeech}


def prepare(language, max_s, overwrite):
    cfg = CORPORA[language]; out = DATA / "EveryVoice" / language; wavs = out / "wavs"; wavs.mkdir(parents=True, exist_ok=True)
    gt = pd.read_csv(REPO / "audios" / language / "ground-truth" / "metadata.csv", dtype=str)
    gt_keys = set(gt.text.map(sentence_key))
    rows, n_new = [], 0
    for r in READERS[language]():
        why = list(r.pop("why")); write = r.pop("write")
        if r["duration_s"] > max_s: why.append(f"longer than {max_s:g} s")
        if not r["text"].strip(): why.append("empty text")
        if sentence_key(r["source_text"]) in gt_keys: why.append("listening-test sentence")
        if re.search(r"[|\n]", r["text"]): why.append("filelist delimiter in text")
        r.update(duration_s=round(r["duration_s"], 3), kept=not why, why="; ".join(why))
        if r["kept"]:
            dst = wavs / f"{r['basename']}.wav"
            if overwrite or not dst.exists():
                if dst.exists(): dst.unlink()
                write(dst); n_new += 1
        rows.append(r)
    df = pd.DataFrame(rows)
    assert df.basename.is_unique, f"{language}: duplicate basenames"
    df.to_csv(out / "transcripts.csv", index=False)
    keep = df[df.kept]
    keep.assign(speaker=cfg["speaker"], language=cfg["language"])[["basename", "text", "speaker", "language"]] \
        .to_csv(out / "metadata.psv", sep="|", index=False, quoting=3)         # quoting=3: QUOTE_NONE, the wizard does not unquote

    # every wav listed in metadata.psv must exist and be mono 16-bit at the corpus rate (the wizard asks for one sample rate)
    fmt = collections.Counter((i.channels, i.samplerate, i.subtype) for i in (sf.info(wavs / f"{b}.wav") for b in keep.basename))
    assert set(fmt) == {(1, cfg["sample_rate"], "PCM_16")}, f"{language}: unexpected wav formats {dict(fmt)}"

    symbols = collections.Counter(c for t in keep.text for c in t)
    letters = {c: n for c, n in symbols.items() if unicodedata.category(c)[0] in "LM"}
    other = {c: n for c, n in symbols.items() if c not in letters}
    dropped = df[~df.kept].why.str.replace(r":.*", "", regex=True).str.split("; ").explode().value_counts().to_dict()
    print(f"== {language}: kept {len(keep)} of {len(df)} utterances, {keep.duration_s.sum() / 3600:.2f} h, "
          f"{keep.duration_s.min():.1f}-{keep.duration_s.max():.1f} s (median {keep.duration_s.median():.1f}); dropped {dropped or 'none'}")
    print(f"   {len(letters)} letter symbols, rarest {min(letters.values())}x: {''.join(sorted(letters))}")
    print(f"   other symbols: {dict(sorted(other.items(), key=lambda x: -x[1]))}")
    print(f"   {n_new} wavs written, {len(keep)} listed -> {out}/metadata.psv  (wizard: wavs dir {wavs}, psv, sample rate {cfg['sample_rate']})")


def main():
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    ap.add_argument("--language", nargs="+", required=True, choices=sorted(CORPORA))
    ap.add_argument("--max-s", type=float, default=15.0, help="drop clips longer than this (seconds)")
    ap.add_argument("--overwrite", action="store_true", help="rewrite wavs that already exist")
    a = ap.parse_args()
    for lang in a.language: prepare(lang, a.max_s, a.overwrite)


if __name__ == "__main__":
    main()