A clean start for the shared repository: the Unity project (Assets, Packages, ProjectSettings), ArtSource, Docs and Tools as they stood at f3666f0 in the old local repository, with its generated prefabs and scene brought up to date. Images, audio, models and binaries go through Git LFS (.gitattributes). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
237 lines
10 KiB
Python
237 lines
10 KiB
Python
"""Every spoken line in the scripted trailer, made whole and then cut: the crew's evening as one Eleven v4 dialogue (four
|
|
voices in one take, so they answer each other), and the Director's and the assistant's calls each read through in one go
|
|
as in the game, with the trailer's phrases cut out of them. A phrase read inside its speech sounds like it; read alone it
|
|
sounds like a line being read.
|
|
|
|
Where each phrase falls in a take is found by listening (faster-whisper's word timings, matched in order against the
|
|
script): the timings the API sends back drift too far to cut by. Whole takes are kept in Tools/audio/eleven_raw/whole_*.wav (+ .json). The crew's lines then go
|
|
through a headset (ArtSource/Trailer/crew), the Director's and the assistant's stay clean (ArtSource/Trailer/boss).
|
|
|
|
ELEVEN_KEY_FILE=... py -I voices.py [again] ("again" makes the whole takes anew)
|
|
"""
|
|
import base64
|
|
import difflib
|
|
import json
|
|
import os
|
|
import re
|
|
import subprocess
|
|
import sys
|
|
|
|
import numpy as np
|
|
|
|
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
ROOT = os.path.normpath(os.path.join(HERE, "..", ".."))
|
|
sys.path.insert(0, os.path.join(ROOT, "Tools", "audio"))
|
|
import eleven # noqa: E402
|
|
|
|
RAW = os.path.join(ROOT, "Tools", "audio", "eleven_raw")
|
|
CREW = os.path.join(ROOT, "ArtSource", "Trailer", "crew")
|
|
BOSS = os.path.join(ROOT, "ArtSource", "Trailer", "boss")
|
|
MODEL = "eleven_v4"
|
|
RATE = 24000
|
|
|
|
FO, GR, EN, TO = "rPMkKgdwgIwqv4fXgR6N", "Q0Co3mt4NHZCSmKqCMMo", "sWsBiVcjjowceAScTnu3", "i9SZdx1xJqqryIiaFdmN"
|
|
DIRECTOR, ASSISTANT = "1BfrkuYXmEwp8AWqSLWk", "fgDJOgmENIR82PueQrVs"
|
|
GA, TA = "[strong Indian accent] ", "[strong Singaporean accent] "
|
|
|
|
# the evening, in the order the trailer tells it
|
|
EVENING = [
|
|
("to_nails", TO, TA + "[deadpan] [quietly] ...these are nail scissors."),
|
|
("fo_rows", FO, "[confident] Okay team. Rows. Straight rows."),
|
|
("gr_big", GR, GA + "[curious] Wait... how big is this planet?"),
|
|
("to_sky", TO, TA + "[awed] [softly] Guys... look at the sky."),
|
|
("fo_hand", FO, "[urgent] Hand it in, hand it in!"),
|
|
("gr_catch", GR, GA + "[mischievously] Catch!"),
|
|
("fo_back", FO, "[excited] [laughs] We are SO back."),
|
|
("en_pickup", EN, "[suspicious] Who took the pickup?"),
|
|
("gr_nobody", GR, GA + "[shouting] [laughing] Nobody!"),
|
|
("en_works", EN, "[proud] It works. It actually works."),
|
|
("en_mostly", EN, "[sighs] ...it mostly works."),
|
|
("to_rain", TO, TA + "[worried] Is the rain... eating the grass?"),
|
|
("fo_save", FO, "[shouting] The bundles! Save the bundles!"),
|
|
("gr_goin", GR, GA + "[excited] [shouting] I'm going in!"),
|
|
("to_did", TO, TA + "[amazed] [softly] We did that?"),
|
|
("fo_did", FO, "[proud] [warmly] We did that."),
|
|
("gr_keep", GR, GA + "[hopeful] Can we keep the combine?"),
|
|
]
|
|
|
|
# their calls, whole, from the game's own scripts; then which phrases the trailer takes out of each
|
|
LINES = json.load(open(os.path.join(ROOT, "Tools", "director", "lines.json"), encoding="utf-8"))["lines"]
|
|
ASST = json.load(open(os.path.join(ROOT, "Tools", "director", "assistant_lines.json"), encoding="utf-8"))["lines"]
|
|
SPEECHES = {
|
|
"intro": (DIRECTOR, LINES["dir_intro"], [("dir_earth", "EARTH IS OUT OF GRASS! NO GRASS!"),
|
|
("dir_scissors", "I don't care if you have to use nail scissors!")]),
|
|
"m100": (DIRECTOR, LINES["dir_m100"], [("dir_did", "You magnificent idiots actually did it.")]),
|
|
"thrown": (ASSISTANT, ASST["asst_thrown"], [("asst_noted", "You got thrown by a twister. [pause] Noted.")]),
|
|
}
|
|
|
|
HEADSET = ("highpass=f=260,lowpass=f=4200,acompressor=threshold=-20dB:ratio=4:attack=5:release=60:makeup=4,"
|
|
"aecho=0.8:0.5:12:0.08,volume=-1dB,alimiter=limit=0.89")
|
|
CLEAN = "apad=pad_dur=0.25,loudnorm=I=-16:TP=-1.5:LRA=11"
|
|
|
|
|
|
def fetch(name, path, payload):
|
|
"""A take with timings, kept; made again only when asked."""
|
|
wav, meta = os.path.join(RAW, f"whole_{name}.wav"), os.path.join(RAW, f"whole_{name}.json")
|
|
if os.path.exists(meta) and "again" not in sys.argv:
|
|
return np.frombuffer(open_pcm(wav), np.int16).astype(np.float32) / 32768, json.load(open(meta))
|
|
d = json.loads(eleven.post(path, payload, accept="application/json"))
|
|
pcm = base64.b64decode(d.pop("audio_base64"))
|
|
os.makedirs(RAW, exist_ok=True)
|
|
eleven.save_pcm(wav, pcm, channels=1, rate=RATE)
|
|
json.dump(d, open(meta, "w"), indent=1)
|
|
print("made", os.path.basename(wav), "%.1fs" % (len(pcm) / 2 / RATE))
|
|
return np.frombuffer(pcm, np.int16).astype(np.float32) / 32768, d
|
|
|
|
|
|
def open_pcm(path):
|
|
import wave
|
|
with wave.open(path) as w:
|
|
return w.readframes(w.getnframes())
|
|
|
|
|
|
def tighten(x, gap=0.3):
|
|
"""Shorten any silence inside a phrase to `gap` seconds: a pause the tag asked for, not a hole."""
|
|
hop = RATE // 100
|
|
e = np.array([np.sqrt(np.mean(x[i:i + hop] ** 2)) for i in range(0, len(x) - hop, hop)])
|
|
quiet = e < max(1e-4, 0.03 * e.max())
|
|
keep = np.ones(len(x), bool)
|
|
i = 0
|
|
while i < len(quiet):
|
|
if quiet[i]:
|
|
j = i
|
|
while j < len(quiet) and quiet[j]:
|
|
j += 1
|
|
if 0 < i and j < len(quiet) and (j - i) * hop > gap * RATE:
|
|
keep[i * hop + int(gap / 2 * RATE):j * hop - int(gap / 2 * RATE)] = False
|
|
i = j
|
|
else:
|
|
i += 1
|
|
return x[keep]
|
|
|
|
|
|
def write(x, out, chain):
|
|
"""Trim the ends, run the chain, 48 kHz mono."""
|
|
trim = "silenceremove=start_periods=1:start_threshold=-40dB,areverse,silenceremove=start_periods=1:start_threshold=-40dB,areverse"
|
|
pcm = (np.clip(x, -1, 1) * 32767).astype(np.int16).tobytes()
|
|
subprocess.run(["ffmpeg", "-v", "error", "-y", "-f", "s16le", "-ar", str(RATE), "-ac", "1", "-i", "-",
|
|
"-af", trim + "," + chain, "-ar", "48000", "-ac", "1", out], input=pcm, check=True)
|
|
|
|
|
|
def words(text):
|
|
"""The words a line says, without its tags, as whisper would spell them."""
|
|
text = re.sub(r"\[[^\]]*\]", " ", text)
|
|
return [w for w in re.sub(r"[^a-z' ]", " ", text.lower()).split() if w]
|
|
|
|
|
|
_heard = None
|
|
|
|
|
|
def heard(x):
|
|
"""Every word in a take, with when it was said (faster-whisper on the CPU)."""
|
|
global _heard
|
|
from faster_whisper import WhisperModel
|
|
if _heard is None:
|
|
_heard = WhisperModel("small.en", device="cpu", compute_type="int8")
|
|
sixteen = np.interp(np.arange(0, len(x), RATE / 16000), np.arange(len(x)), x).astype(np.float32)
|
|
segs, _ = _heard.transcribe(sixteen, beam_size=5, word_timestamps=True)
|
|
out = []
|
|
for sg in segs:
|
|
for w in sg.words:
|
|
for part in words(w.word):
|
|
out.append((part, w.start, w.end))
|
|
return out
|
|
|
|
|
|
def place(x, lines):
|
|
"""Where each line (a list of words) was said in the take: matched in order against what whisper heard. The
|
|
timings the API sends with a dialogue only say which input is which, not where its speech is."""
|
|
got = heard(x)
|
|
flat, owner = [], []
|
|
for k, ws in enumerate(lines):
|
|
flat += ws
|
|
owner += [k] * len(ws)
|
|
sm = difflib.SequenceMatcher(None, flat, [g[0] for g in got], autojunk=False)
|
|
hit = {}
|
|
for a, b, n in sm.get_matching_blocks():
|
|
for i in range(n):
|
|
k = owner[a + i]
|
|
s, e = got[b + i][1], got[b + i][2]
|
|
lo, hi = hit.get(k, (s, e))
|
|
hit[k] = (min(lo, s), max(hi, e))
|
|
missing = [k for k in range(len(lines)) if k not in hit]
|
|
if missing:
|
|
raise SystemExit("not heard: " + ", ".join(" ".join(lines[k]) for k in missing))
|
|
return [hit[k] for k in range(len(lines))]
|
|
|
|
|
|
def gap(x, a, b):
|
|
"""The quietest moment between a and b seconds: the middle of the longest near-silence, else the softest 10 ms.
|
|
Whisper's word ends run late and its starts early, so lines are parted here, not at its timings."""
|
|
hop = RATE // 100
|
|
lo, hi = int(max(0, a) * RATE), int(min(len(x) / RATE, b) * RATE)
|
|
e = np.array([np.sqrt(np.mean(x[i:i + hop] ** 2)) + 1e-9 for i in range(lo, max(lo + 1, hi - hop), hop)])
|
|
db = 20 * np.log10(e)
|
|
quiet = db < -50
|
|
best, run, start = (0, 0), 0, 0
|
|
for i, q in enumerate(quiet):
|
|
if q:
|
|
if run == 0:
|
|
start = i
|
|
run += 1
|
|
if run > best[0]:
|
|
best = (run, start)
|
|
else:
|
|
run = 0
|
|
k = best[1] + best[0] // 2 if best[0] else int(np.argmin(db))
|
|
return (lo + k * hop) / RATE
|
|
|
|
|
|
def cut(x, spans, k):
|
|
"""Line k's stretch: from the quiet before it to the quiet after it (the ends are trimmed to the voice afterwards)."""
|
|
a, b = spans[k]
|
|
lo = gap(x, spans[k - 1][1] - 0.3, a + 0.2) if k > 0 else 0.0
|
|
hi = gap(x, b - 0.2, spans[k + 1][0] + 0.6) if k + 1 < len(spans) else len(x) / RATE
|
|
return x[int(lo * RATE):int(hi * RATE)]
|
|
|
|
|
|
def evening():
|
|
x, _ = fetch("evening", f"/text-to-dialogue/with-timestamps?output_format=pcm_{RATE}",
|
|
{"model_id": MODEL, "inputs": [{"text": t, "voice_id": v} for _, v, t in EVENING]})
|
|
spans = place(x, [words(t) for _, _, t in EVENING])
|
|
os.makedirs(CREW, exist_ok=True)
|
|
for k, (name, _, _) in enumerate(EVENING):
|
|
write(tighten(cut(x, spans, k)), os.path.join(CREW, name + ".wav"), HEADSET)
|
|
print(f"{name:12s} {spans[k][0]:6.2f}-{spans[k][1]:6.2f}")
|
|
|
|
|
|
def speeches():
|
|
os.makedirs(BOSS, exist_ok=True)
|
|
for name, (voice, text, cuts) in SPEECHES.items():
|
|
x, _ = fetch(name, f"/text-to-speech/{voice}/with-timestamps?output_format=pcm_{RATE}",
|
|
{"model_id": MODEL, "text": text, "voice_settings": {"stability": 0.5}})
|
|
# the whole speech in sentences, so each phrase is matched where it really falls
|
|
parts, which = [], {}
|
|
rest = text
|
|
for out, phrase in cuts:
|
|
i = rest.find(phrase)
|
|
if i < 0:
|
|
raise SystemExit(f"{name}: no '{phrase}' in its script")
|
|
if words(rest[:i]):
|
|
parts.append(words(rest[:i]))
|
|
which[out] = len(parts)
|
|
parts.append(words(phrase))
|
|
rest = rest[i + len(phrase):]
|
|
if words(rest):
|
|
parts.append(words(rest))
|
|
spans = place(x, parts)
|
|
for out, _ in cuts:
|
|
k = which[out]
|
|
write(tighten(cut(x, spans, k)), os.path.join(BOSS, out + ".wav"), CLEAN)
|
|
print(f"{out:12s} {spans[k][0]:6.2f}-{spans[k][1]:6.2f}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
evening()
|
|
speeches()
|