Files
ComfyGen/generate_voice.py

167 lines
7.5 KiB
Python
Raw Permalink Normal View History

"""
Narrator voice for the intro, generated locally with Chatterbox Multilingual.
Runs in its own venv (Chatterbox pins torch 2.6), see .venv-tts:
.venv-tts\\Scripts\\python.exe generate_voice.py all languages
.venv-tts\\Scripts\\python.exe generate_voice.py de one language
.venv-tts\\Scripts\\python.exe generate_voice.py de intro.line1 one line
Texts come straight from ../Languages/<lang>.json. Each line is rendered to
output/voice/<lang>/<key>.wav, then trimmed, loudness-normalised and written as
../Assets/Audio/voice_<lang>_<key with _ instead of .>.mp3 (embedded in the exe).
.venv-tts\\Scripts\\python.exe generate_voice.py --cards [de] [--skip-existing]
every event card ("Title. Body")
Female and male narrator alternate (voice_refs/, made by make_voice_refs.py);
Chatterbox clones the reference timbre into every language.
Chatterbox sometimes keeps babbling after the sentence or swallows words, so every
take is transcribed with Whisper and only accepted when the words match and the
length is plausible and the pitch fits the wanted voice; otherwise the next seed
is tried (best take wins).
"""
import _bootstrap # Projektordner (config.py, Listen) vor allen anderen Modulen
import config
import difflib
import re
import json
import os
import subprocess
import sys
import librosa
import numpy as np
import torch
import torchaudio as ta
from chatterbox.mtl_tts import ChatterboxMultilingualTTS
from faster_whisper import WhisperModel
HERE = os.path.dirname(os.path.abspath(__file__))
LANG_DIR = config.LANG_DIR
AUDIO_DIR = os.path.join(config.ASSETS_DIR, "Audio")
RAW_DIR = os.path.join(config.OUTPUT_DIR, "voice")
# Welche Texte gesprochen werden, kommt aus dem Projekt: config.VOICE_MODULE
import importlib as _il
_d = _il.import_module(getattr(config, "VOICE_MODULE", "voice_life"))
LANGS, KEYS, VOICE_OF = _d.LANGS, _d.KEYS, _d.VOICE_OF
REFS = os.path.join(HERE, "voice_refs")
# calm storyteller: little exaggeration, low cfg = slower, more relaxed pacing
EXAGGERATION = 0.4
CFG_WEIGHT = 0.5 # Englisch; andere Sprachen 0, sonst färbt der englische Akzent der Referenz ab
TEMPERATURE = 0.7
SEED = int(os.environ.get("VOICE_SEED", 7)) # anderer Startwert für einen Satz: set VOICE_SEED=100
TRIES = 12
MIN_MATCH = 0.98 # buchstabenweise; 0,97 ließ noch "Entschiedung" durch
CHARS_PER_SEC = 8.0 # slower than this = babbling / long pauses
SPOKEN = _d.SPOKEN
# trim silence at both ends, gentle fade, broadcast-ish loudness
FILTER = ("silenceremove=start_periods=1:start_threshold=-45dB:start_silence=0.05,"
"areverse,silenceremove=start_periods=1:start_threshold=-45dB:start_silence=0.1,areverse,"
"afade=t=in:d=0.03,loudnorm=I=-18:TP=-2:LRA=7")
def mp3_name(lang, key):
return f"voice_{lang}_{key.replace('.', '_')}.mp3"
def norm(t):
# buchstabenweise, ohne Leerzeichen: "Weg teilst" == "wegteilst"
return re.sub(r"[^\w]+", "", t.lower().replace("ß", "ss"))
def match(a, b):
return difflib.SequenceMatcher(None, norm(a), norm(b)).ratio()
def pitch_ok(wav, sr, voice):
"""Grobe Geschlechtsprüfung über die mittlere Tonhöhe (Frau ~165+ Hz, Mann ~150- Hz)."""
y = librosa.resample(wav, orig_sr=sr, target_sr=16000)
f0, voiced, _ = librosa.pyin(y, fmin=60, fmax=400, sr=16000)
f0 = f0[voiced]
if len(f0) == 0:
return False, 0.0
med = float(np.median(f0))
return (med >= 160 if voice == "female" else med <= 155), med
def card_ids():
"""Karten-Ids in der Reihenfolge von EventCardSystem.cs (für den Stimmenwechsel)."""
src = open(config.CARDS_FILE, encoding="utf-8-sig").read()
return re.findall(r'^\s+new\("([a-z_0-9]+)", "', src, re.M)
def items_for(texts, args):
"""(key, Untertitel-Text, Stimme) — Intro-Sätze oder alle Karten."""
if "--cards" in args:
ids = [a[5:] for a in args if a.startswith("card.")] or card_ids()
order = card_ids()
out = []
for cid in ids:
title, body = texts[f"card.{cid}.title"], texts[f"card.{cid}.body"]
text = f"{title.rstrip('.!?…')}. {body}"
out.append((f"card.{cid}", text, "female" if order.index(cid) % 2 == 0 else "male"))
return out
if "--album" in args:
keys = [k for k in texts if k.startswith("album.voice.")]
only = [a for a in args if a.startswith("album.voice.")] # einzelne Sätze neu erzeugen
return [(k, texts[k], "female" if i % 2 == 0 else "male") for i, k in enumerate(keys) if not only or k in only]
keys = [a for a in args if a in KEYS] or KEYS
return [(k, texts[k], VOICE_OF[k]) for k in keys]
def main():
args = sys.argv[1:]
langs = [a for a in args if a in LANGS] or LANGS
skip = "--skip-existing" in args
min_match = 0.95 if "--cards" in args else MIN_MATCH # Album-Sätze sind kurz → streng # lange Texte: Whisper weicht minimal ab
device = "cuda" if torch.cuda.is_available() else "cpu"
model = ChatterboxMultilingualTTS.from_pretrained(device=device)
whisper = WhisperModel("small", device="cpu", compute_type="int8")
for lang in langs:
texts = json.load(open(os.path.join(LANG_DIR, f"{lang}.json"), encoding="utf-8"))
os.makedirs(os.path.join(RAW_DIR, lang), exist_ok=True)
for key, text, voice in items_for(texts, args):
dest = os.path.join(AUDIO_DIR, mp3_name(lang, key))
if skip and os.path.exists(dest):
continue
raw = os.path.join(RAW_DIR, lang, key + ".wav")
tmp = os.path.join(RAW_DIR, lang, key + ".try.wav")
max_len = max(3.2, len(text) / CHARS_PER_SEC) # kurze Sätze brauchen mit Pausen ~3 s
best = (-1.0, None, "")
for attempt in range(TRIES):
torch.manual_seed(SEED + attempt)
wav = model.generate(SPOKEN.get((lang, key), text), language_id=lang,
audio_prompt_path=os.path.join(REFS, f"{voice}.wav"),
exaggeration=EXAGGERATION, temperature=TEMPERATURE,
cfg_weight=CFG_WEIGHT if lang == "en" else 0.0)
ta.save(tmp, wav, model.sr)
dur = wav.shape[-1] / model.sr
# direkt als 16-kHz-Array (Whisper' eigener Datei-Loader verträgt die av-Version nicht)
pcm = ta.functional.resample(wav.cpu(), model.sr, 16000)[0].numpy().astype("float32")
segs, _ = whisper.transcribe(pcm, language=lang, beam_size=5)
heard = " ".join(sg.text for sg in segs).strip()
good_pitch, f0 = pitch_ok(wav[0].cpu().numpy(), model.sr, voice)
score = match(text, heard) - (0.5 if dur > max_len else 0) - (0.5 if not good_pitch else 0)
print(f" try {attempt}: {voice} {f0:3.0f} Hz {dur:4.1f} s match {score:.2f} '{heard}'", flush=True)
if score > best[0]:
best = (score, dur, heard)
os.replace(tmp, raw)
if score >= min_match:
break
if os.path.exists(tmp):
os.remove(tmp)
if best[0] < min_match:
print(f"!! {lang} {key}: best take only {best[0]:.2f}", flush=True)
subprocess.run(["ffmpeg", "-y", "-loglevel", "error", "-i", raw, "-af", FILTER,
"-ac", "1", "-ar", "44100", "-b:a", "96k", dest], check=True)
print(f"{lang} {key:14s} {voice:6s} {best[1]:4.1f} s match {best[0]:.2f} {text}", flush=True)
if __name__ == "__main__":
main()