thucdangvan020999's picture
Initial upload: releases, checkpoints, code, docs
a1fe2e2 verified
Raw History Blame Contribute Delete
9.62 kB
"""Synthesise keyword, hard-negative and negative clips with TTS voices.
Takes the phrase list from ``vitakws-phrases`` and a voice list
(``configs/voices_vi.yaml``), and writes 16 kHz clips plus a manifest.
Back ends
edge Microsoft Edge online voices through the ``edge-tts`` package.
Sends the text to Microsoft's service; needs internet.
piper a local Piper voice (``piper --model x.onnx``); fully offline.
command any TTS you can run from a shell, for voice-cloning models:
``command: "python my_tts.py --ref spk.wav --text {text} --out {out}"``
Keyword clips can have a command appended ("hây vi ta" + "mở cửa sổ"). The two
parts are synthesised separately and joined, so the keyword end time written to
the manifest is exact.
vitakws-synth --phrases data/phrases.tsv --voices configs/voices_vi.yaml --out data/tts
"""
from __future__ import annotations
import argparse
import asyncio
import hashlib
import json
import shlex
import subprocess
import sys
import tempfile
import time
from pathlib import Path
import numpy as np
import yaml
from vitakws.data import audio
from vitakws.data.manifest import NEGATIVE_KINDS, Item, read_manifest, write_manifest
from vitakws.tools.phrases import read_phrases
SR = 16000
TRIM_MARGIN = 0.08 # seconds of context kept around the spoken part
MIN_SPEECH = 0.25 # shorter than this means the engine produced nothing useful
EDGE_RETRIES = 5
EDGE_BACKOFF = 1.0 # seconds, multiplied by the attempt number
class SynthError(RuntimeError):
pass
def synth_edge(text: str, voice: dict, variation: dict, out: Path) -> None:
import edge_tts
kwargs = {k: variation[k] for k in ("rate", "pitch", "volume") if k in variation}
# The free endpoint drops requests at random ("no audio received"), so retry.
last: Exception | None = None
for attempt in range(EDGE_RETRIES):
try:
asyncio.run(edge_tts.Communicate(text, voice["voice"], **kwargs).save(str(out)))
if out.exists() and out.stat().st_size > 0:
return
last = SynthError("empty response")
except Exception as e: # edge-tts raises its own exception types plus network errors
last = e
time.sleep(EDGE_BACKOFF * (attempt + 1))
raise SynthError(f"edge-tts failed for {text!r} after {EDGE_RETRIES} tries: {last}")
def synth_piper(text: str, voice: dict, variation: dict, out: Path) -> None:
cmd = [
*shlex.split(voice.get("executable", "piper")),
"--model",
voice["model"],
"--output_file",
str(out),
]
for key in ("length_scale", "noise_scale", "noise_w", "speaker"):
if key in variation:
cmd += [f"--{key}", str(variation[key])]
run(cmd, text)
def synth_command(text: str, voice: dict, variation: dict, out: Path) -> None:
fields = {"text": text, "out": str(out), **{k: str(v) for k, v in variation.items()}}
run([part.format(**fields) for part in shlex.split(voice["command"])], None)
def run(cmd: list[str], stdin_text: str | None) -> None:
try:
proc = subprocess.run(
cmd, input=stdin_text, text=True, capture_output=True, timeout=300, check=False
)
except (OSError, subprocess.TimeoutExpired) as e:
raise SynthError(f"{cmd[0]}: {e}") from e
if proc.returncode != 0:
raise SynthError(f"{cmd[0]} exited {proc.returncode}: {proc.stderr.strip()[-300:]}")
BACKENDS = {
"edge": (synth_edge, ".mp3"),
"piper": (synth_piper, ".wav"),
"command": (synth_command, ".wav"),
}
def clip_key(text: str, voice: dict, variation: dict) -> str:
blob = json.dumps([text, voice["id"], variation], sort_keys=True, ensure_ascii=False)
return hashlib.sha1(blob.encode()).hexdigest()[:16]
def speak(text: str, voice: dict, variation: dict, cache: Path) -> np.ndarray:
"""Trimmed 16 kHz speech for one text; cached on disk so reruns are free."""
cached = cache / f"{clip_key(text, voice, variation)}.wav"
if cached.exists():
return audio.load(cached, SR)
synth, suffix = BACKENDS[voice["backend"]]
with tempfile.TemporaryDirectory() as tmp:
raw = Path(tmp) / f"raw{suffix}"
synth(text, voice, variation, raw)
if not raw.exists() or raw.stat().st_size == 0:
raise SynthError(f"{voice['id']} produced no audio for {text!r}")
wave = audio.load(raw, SR)
start, end = audio.active_region(wave, SR)
margin = int(TRIM_MARGIN * SR)
wave = wave[max(0, start - margin) : min(len(wave), end + margin)]
if len(wave) < MIN_SPEECH * SR or audio.rms(wave) < 1e-4:
raise SynthError(f"{voice['id']} produced silence for {text!r}")
peak = float(np.abs(wave).max())
wave = (wave * (0.7 / peak)).astype(np.float32)
audio.save(cached, wave, SR)
return wave
def load_voices(path: str | Path) -> list[dict]:
with open(path, encoding="utf-8") as f:
voices = yaml.safe_load(f)["voices"]
for voice in voices:
for key in ("id", "backend"):
if key not in voice:
raise ValueError(f"{path}: a voice is missing {key!r}: {voice}")
if voice["backend"] not in BACKENDS:
raise ValueError(
f"{path}: voice {voice['id']} has unknown backend {voice['backend']!r}"
)
voice.setdefault("variations", [{}])
return voices
def main(argv: list[str] | None = None) -> None:
parser = argparse.ArgumentParser(
description=__doc__, formatter_class=argparse.RawTextHelpFormatter
)
parser.add_argument("--phrases", required=True, help="TSV from vitakws-phrases")
parser.add_argument("--voices", required=True, help="YAML voice list")
parser.add_argument("--out", required=True, help="output folder")
parser.add_argument("--labels", nargs="*", help="only these labels (default: all but carriers)")
parser.add_argument(
"--variations-per-text",
type=int,
default=0,
help="random subset of each voice's variations per text; 0 uses all",
)
parser.add_argument(
"--carrier-prob",
type=float,
default=0.5,
help="share of keyword clips that get a command appended",
)
parser.add_argument(
"--limit", type=int, default=0, help="stop after this many clips (0 = no limit)"
)
parser.add_argument("--seed", type=int, default=0)
args = parser.parse_args(argv)
rows = read_phrases(args.phrases)
voices = load_voices(args.voices)
carriers = [text for label, text, _ in rows if label == "carrier"]
wanted = [r for r in rows if r[0] != "carrier" and (not args.labels or r[0] in args.labels)]
out = Path(args.out)
cache = out / "cache"
rng = np.random.default_rng(args.seed)
manifest_path = out / "manifest.jsonl"
items = {i.audio: i for i in read_manifest(manifest_path)} if manifest_path.exists() else {}
made, failures = 0, []
for voice in voices:
for label, text, origin in wanted:
variations = voice["variations"]
if args.variations_per_text and len(variations) > args.variations_per_text:
picks = rng.choice(len(variations), size=args.variations_per_text, replace=False)
variations = [variations[int(i)] for i in sorted(picks)]
for variation in variations:
if args.limit and made >= args.limit:
break
is_keyword = label not in NEGATIVE_KINDS
carrier = ""
if is_keyword and carriers and rng.random() < args.carrier_prob:
carrier = carriers[int(rng.integers(len(carriers)))]
gap = float(rng.uniform(0.05, 0.30))
try:
wave = speak(text, voice, variation, cache)
kw_start, kw_end = TRIM_MARGIN, len(wave) / SR - TRIM_MARGIN
if carrier:
tail = speak(carrier, voice, variation, cache)
wave = np.concatenate([wave, np.zeros(int(gap * SR), np.float32), tail])
except SynthError as e:
failures.append(str(e))
continue
name = clip_key(f"{text}|{carrier}", voice, variation)
path = out / "audio" / label / f"{voice['id']}_{name}.wav"
audio.save(path, wave, SR)
item = Item(
audio=str(path.resolve()),
label=label,
split="train",
speaker=f"tts_{voice['id']}",
gender=voice.get("gender", "unknown"),
region=voice.get("region", "unknown"),
source=f"tts:{voice['backend']}:{voice['id']}",
env="clean",
text=f"{text} {carrier}".strip(),
duration=round(len(wave) / SR, 4),
extra={"origin": origin, "variation": variation},
)
if is_keyword:
item.kw_start, item.kw_end = round(kw_start, 4), round(kw_end, 4)
items[item.audio] = item
made += 1
write_manifest(manifest_path, items.values())
print(f"synthesised {made} clips; {manifest_path} has {len(items)} items")
if failures:
print(f"{len(failures)} clips failed, first few:", file=sys.stderr)
for line in failures[:5]:
print(f" {line}", file=sys.stderr)
if made == 0:
sys.exit(1)
if __name__ == "__main__":
main()