Files
dotfiles/scripts/build-sound-theme.py
Ziad ArafatandClaude Opus 5.5 86876cd7a4 Sounds: Portal 2 voice lines for rare events, ffmpeg PCM conversion + loudness normalisation
Picked by transcribing turret clips (Whisper) and matching the rest against the
game's English captions. Voice lines (turrets, GLaDOS, Wheatley, announcer,
space core) for login/lock/devices/power/network/dialogs; short effects stay on
frequent events. Voice lines are MP3 frames named .wav, so build-sound-theme now
re-encodes everything to PCM via ffmpeg with loudnorm (-14 LUFS).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013UzjWUxheYfqqjWGH7Ktmc
2026-10-30 15:29:51 -06:00

105 lines
3.9 KiB
Python

"""Build a freedesktop sound theme from Portal 2's own sound files.
build-sound-theme # build + activate ~/.local/share/sounds/portal2
build-sound-theme --list PATTERN # explore the VPK, e.g. --list '*turret*'
Game assets can't live in git, so this extracts them from your local Steam
install. Each freedesktop event takes the first VPK path matching one of its
glob patterns; edit config/sounds/portal2.json to retune.
"""
import argparse
import fnmatch
import json
import os
import re
import subprocess
import tempfile
from pathlib import Path
import vpk
HOME = Path.home()
# Read from the checkout (not next to this script, which lives in the Nix store) so edits apply without a switch.
MAPPING = Path(os.environ.get("DOTFILES_DIR", HOME / ".dotfiles")) / "config/sounds/portal2.json"
THEME = "portal2"
def steam_libraries() -> list[Path]:
roots = [HOME / ".local/share/Steam", HOME / ".steam/steam", HOME / ".var/app/com.valvesoftware.Steam/.local/share/Steam"]
libs = []
for root in roots:
vdf = root / "steamapps/libraryfolders.vdf"
if vdf.is_file():
libs += [Path(p) for p in re.findall(r'"path"\s+"([^"]+)"', vdf.read_text())]
libs.append(root)
return list(dict.fromkeys(libs))
def find_vpks() -> list[Path]:
found = []
for lib in steam_libraries():
game = lib / "steamapps/common/Portal 2"
for sub in ("portal2", "portal2_dlc1", "portal2_dlc2"):
p = game / sub / "pak01_dir.vpk"
if p.is_file():
found.append(p)
return found
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--list", metavar="PATTERN")
ap.add_argument("--no-activate", action="store_true")
args = ap.parse_args()
paks = [vpk.open(str(p)) for p in find_vpks()]
if not paks:
raise SystemExit("Portal 2 not found in any Steam library; install it and re-run")
index = {}
for pak in paks:
for path in pak:
if path.startswith("sound/") and path.endswith((".wav", ".mp3")):
index.setdefault(path, pak)
if args.list:
for path in sorted(index):
if fnmatch.fnmatch(path, args.list):
print(path)
return
mapping = json.loads(MAPPING.read_text())
out = HOME / ".local/share/sounds" / THEME / "stereo"
out.mkdir(parents=True, exist_ok=True)
for event, patterns in mapping["events"].items():
match = next((p for pat in patterns for p in sorted(index) if fnmatch.fnmatch(p, pat)), None)
if not match:
print(f"-- {event}: no match for {patterns}")
continue
for old in out.glob(f"{event}.*"):
old.unlink()
# Voice lines are raw MP3 frames named .wav, which canberra can't decode; re-encode
# everything as PCM and loudness-normalise so voices and blips play at one level.
with tempfile.NamedTemporaryFile(suffix=Path(match).suffix) as src:
src.write(index[match].get_file(match).read())
src.flush()
subprocess.run(
["ffmpeg", "-loglevel", "error", "-y", "-i", src.name,
"-af", "loudnorm=I=-14:TP=-1.0:LRA=11", "-ar", "48000", "-ac", "2", "-c:a", "pcm_s16le",
str(out / f"{event}.wav")],
check=True,
)
caption = mapping.get("_captions", {}).get(event, "")
print(f"ok {event:24} <- {match}{' \u201c' + caption + '\u201d' if caption else ''}")
(out.parent / "index.theme").write_text(
f"[Sound Theme]\nName=Portal 2\nComment=Aperture Science approved notifications\nInherits=ocean,freedesktop\nDirectories=stereo\n\n[stereo]\nOutputProfile=stereo\n"
)
if not args.no_activate:
subprocess.run(["kwriteconfig6", "--file", "kdeglobals", "--group", "Sounds", "--key", "Theme", THEME], check=False)
print(f"activated sound theme '{THEME}'")
if __name__ == "__main__":
main()