Files
GladiatorIdle/tools/make_oath_voice.py
2026-11-09 21:43:38 +01:00

166 lines
8.0 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Die Rede nach der Erstellung mit der Kriegerstimme vorab sprechen (Chatterbox, Referenz
_Tools/ComfyGen/voice_refs/warrior.wav), jeden Satz mit Whisper geprüft (bester Versuch gewinnt).
Ziel: Assets/Voices/oath/<de|en|es>/
line1.wav … line5.wav Sätze ohne Namen (Text aus Languages/<lang>.json, "oath.text")
names/<schlüssel>.wav erster Satz „Mein Name ist X.“ für häufige Namen (NAMES)
prefix.wav „Mein Name ist“ allein – für Namen ohne eigene Aufnahme
Das Spiel (Core/NameVoice.cs) setzt daraus die Rede zusammen; Hall und Mischung macht es selbst.
_Tools\\ComfyGen\\.venv-tts\\Scripts\\python.exe tools/make_oath_voice.py fehlende erzeugen
… make_oath_voice.py --force alles neu
… make_oath_voice.py --lang de --names 0 nur Deutsch, keine Namen
"""
import argparse, difflib, json, os, re, unicodedata
import numpy as np
import soundfile as sf
import torch
import torchaudio as ta
ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")
REF = os.path.join(ROOT, "..", "_Tools", "ComfyGen", "voice_refs", "warrior.wav")
DEST = os.path.join(ROOT, "Assets", "Voices", "oath")
# Häufige Namen für Gladiatoren: römisch/legendär und gängige Vornamen (de/en/es)
# Die ersten zuerst (mit --names N nur die häufigsten)
TOP = "Spartacus Maximus Marcus Lucius Crixus Michael Alex Max Thomas Daniel David Lukas Leon Paul Peter John James Chris Mike Carlos Juan Pablo Diego Jose Luis Hector Achilles Leonidas Titus Brutus".split()
NAMES = """Spartacus Maximus Crixus Flamma Priscus Verus Carpophorus Commodus Marcus Lucius Gaius Titus Quintus
Decimus Tiberius Julius Brutus Cassius Severus Aurelius Octavius Felix Atticus Cato Nero Hector Achilles Ajax
Leonidas Ares Mars Thor Odin Ragnar Conan Arthur Attila Hannibal Varus Magnus Rufus Drusus Gallus
Michael Michi Max Alex Alexander Paul Peter Thomas Daniel David Jan Lukas Leon Finn Jonas Tim Tom Ben Noah
Elias Luca Kevin Dennis Marco Sven Stefan Markus Florian Tobias Simon Sebastian Christian Andreas Martin
Patrick Robert Kai Nico Erik Viktor Ivan Igor Oliver Liam Ethan Lucas Mateo Adrian Hugo Mario Leo John James
Jack Ryan Chris Mike Steve Sam Carlos Juan Pedro Diego Pablo Javier Miguel Antonio Jose Luis Sergio Raul
Alejandro Manuel Fernando Rafael""".split()
NAMES = TOP + [n for n in NAMES if n not in TOP]
WHISPER_LANG = {"de": "de", "en": "en", "es": "es"}
def key(name):
"""Dateiname wie im Spiel (NameVoice.OathKey): klein, ohne Akzente, nur a–z."""
s = unicodedata.normalize("NFD", name.lower())
return "".join(c for c in s if "a" <= c <= "z")
def norm(t):
s = unicodedata.normalize("NFD", t.lower())
s = "".join(c for c in s if not unicodedata.combining(c))
return " ".join(re.sub(r"[^a-zß ]", " ", s).split())
def lines_of(lang):
with open(os.path.join(ROOT, "Languages", lang + ".json"), encoding="utf-8") as f:
return [p.strip() for p in json.load(f)["oath.text"].split("|") if p.strip()]
class Voice:
def __init__(self):
from chatterbox.mtl_tts import ChatterboxMultilingualTTS
from faster_whisper import WhisperModel
self.tts = ChatterboxMultilingualTTS.from_pretrained(device="cuda" if torch.cuda.is_available() else "cpu")
self.whisper = WhisperModel("small", device="cpu", compute_type="int8")
self.sr = self.tts.sr
def hear(self, wav, lang, words=False):
pcm = ta.functional.resample(torch.from_numpy(wav)[None], self.sr, 16000)[0].numpy().astype("float32")
segs, _ = self.whisper.transcribe(pcm, language=WHISPER_LANG[lang], beam_size=5, word_timestamps=words)
segs = list(segs)
return " ".join(s.text for s in segs), [w for s in segs for w in (s.words or [])]
def say(self, text, lang, tries=4, seed=21):
"""Bester von mehreren Versuchen (Whisper-Ähnlichkeit, zu lang = Gebrabbel)."""
best = (-9.0, None, "")
for attempt in range(tries):
torch.manual_seed(seed + attempt)
wav = self.tts.generate(text, language_id=lang, audio_prompt_path=REF,
exaggeration=0.95, temperature=0.8, cfg_weight=0.0)[0].cpu().numpy()
wav = trim(wav)
heard, _ = self.hear(wav, lang)
score = difflib.SequenceMatcher(None, norm(text), norm(heard)).ratio()
if len(wav) / self.sr > len(text) / 7 + 2: score -= 0.4
if score > best[0]: best = (score, wav, heard)
if score > 0.95: break
return best
def trim(a, thr=0.01):
nz = np.where(np.abs(a) > thr)[0]
if len(nz) == 0: return a
a = a[max(0, nz[0] - 240):nz[-1] + 1200]
return a
def save(path, a, sr):
os.makedirs(os.path.dirname(path), exist_ok=True)
a = a / (np.abs(a).max() + 1e-6) * 0.9
sf.write(path, a.astype(np.float32), sr, subtype="PCM_16")
def cut_after_name(v, wav, lang, n_prefix):
"""Gebrabbel nach dem Namen abschneiden (Ende des Namenworts laut Whisper + kurzer Ausklang)."""
_, words = v.hear(wav, lang, words=True)
if len(words) > n_prefix + 1:
end = min(len(wav), int((words[n_prefix].end + 0.18) * v.sr))
wav = wav[:end]
return wav
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--lang", default="de,en,es")
ap.add_argument("--names", type=int, default=len(NAMES), help="wie viele Namen (0 = keine)")
ap.add_argument("--tries", type=int, default=3, help="Versuche je Name")
ap.add_argument("--force", action="store_true")
ap.add_argument("--fix", default="", help="vorhandene Namen nachträglich kürzen: lang:Name,lang:Name")
args = ap.parse_args()
v = Voice()
if args.fix == "all": # alle vorhandenen Namen
args.fix = ",".join(f"{l}:{f[:-4]}" for l in args.lang.split(",")
for f in sorted(os.listdir(os.path.join(DEST, l, "names"))))
for item in filter(None, args.fix.split(",")):
lang, name = item.split(":")
p = os.path.join(DEST, lang, "names", key(name) + ".wav")
wav, sr = sf.read(p, dtype="float32")
before = len(wav)
wav = cut_after_name(v, wav, lang, len(lines_of(lang)[0].split("{0}")[0].split()))
if len(wav) < before:
save(p, wav, sr)
print(f"fixed {item}: {before / sr:.2f}s -> {len(wav) / sr:.2f}s", flush=True)
if args.fix: return
for lang in args.lang.split(","):
out = os.path.join(DEST, lang)
lines = lines_of(lang)
# Sätze 2…6 (ohne Namen)
for i, text in enumerate(lines[1:], 1):
p = os.path.join(out, f"line{i}.wav")
if os.path.exists(p) and not args.force: continue
score, wav, heard = v.say(text, lang)
save(p, wav, v.sr)
print(f"{lang} line{i}: {score:.2f} '{heard.strip()}'", flush=True)
# „Mein Name ist“ allein: aus einem ganzen Satz an der Wortgrenze vor dem Namen geschnitten
p = os.path.join(out, "prefix.wav")
if not os.path.exists(p) or args.force:
n_prefix = len(lines[0].split("{0}")[0].split())
for seed in range(31, 41):
score, wav, _ = v.say(lines[0].replace("{0}", "Spartacus"), lang, tries=1, seed=seed)
_, words = v.hear(wav, lang, words=True)
if score > 0.85 and len(words) > n_prefix:
cut = (words[n_prefix - 1].end + words[n_prefix].start) / 2
save(p, wav[:int(cut * v.sr)], v.sr)
print(f"{lang} prefix: {score:.2f} cut {cut:.2f}s", flush=True)
break
# erster Satz mit Namen
for name in NAMES[:args.names]:
p = os.path.join(out, "names", key(name) + ".wav")
if os.path.exists(p) and not args.force: continue
score, wav, heard = v.say(lines[0].replace("{0}", name), lang, tries=args.tries)
wav = cut_after_name(v, wav, lang, len(lines[0].split("{0}")[0].split()))
save(p, wav, v.sr)
print(f"{lang} {name}: {score:.2f} '{heard.strip()}'", flush=True)
print("done")
if __name__ == "__main__":
main()