Something went wrong. Try again.
Something went wrong. Try again.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465"""Lyric line starts and beats for a song: the timing backbone of the shot list.
Reads the lyric subtitles embedded in the song file (Suno .m4a exports carry an SRT track), refines each line start tothe actual vocal onset on the vocal stem, detects beats on the drum stem, and writes <out>/lyrics.json + <out>/beats.json.
uv run --with librosa --with soundfile python previz/align.py --song song.m4a \ --vocals stems/vocals.wav --drums stems/drums.wav [--out previz]
Without an embedded subtitle track, pass --lyrics lines.txt ("<seconds> <text>" per line, rough times are fine).
NOTE: embedded subtitle timestamps can be off by up to ~2.5 s. Problem lines are best re-anchored against Whisper wordtimings on the vocal stem (save them as words.json) and corrected by hand in lyrics.json; re-running this scriptoverwrites those corrections.Stems: Suno's stems zip, or Demucs (`uv run --with demucs python -m demucs --two-stems=vocals song.m4a`)."""import argparse, json, pathlib, re, subprocessimport numpy as np, soundfile as sf, librosa
ap = argparse.ArgumentParser()ap.add_argument("--song", required=True, help="song file (for the embedded subtitle track)")ap.add_argument("--vocals", required=True, help="vocal stem (wav)")ap.add_argument("--drums", required=True, help="drum stem (wav); the full mix works too, less reliably")ap.add_argument("--lyrics", help="text file '<seconds> <line>' instead of the embedded subtitles")ap.add_argument("--out", default=str(pathlib.Path(__file__).resolve().parent), help="output folder")a = ap.parse_args()OUT = pathlib.Path(a.out)
if a.lyrics: lines = [(float(t), txt.strip()) for t, txt in (l.split(None, 1) for l in open(a.lyrics, encoding="utf-8") if l.strip())]else: srt = subprocess.run(["ffmpeg", "-v", "error", "-i", a.song, "-map", "0:s:0", "-f", "srt", "-"], capture_output=True, text=True, check=True).stdout ts = lambda h, m, s, ms: int(h) * 3600 + int(m) * 60 + int(s) + int(ms) / 1000 lines = [(ts(*m.group(1, 2, 3, 4)), m.group(5).strip()) for m in re.finditer(r"(\d+):(\d+):(\d+),(\d+) --> .*?\n(.+)", srt) if not m.group(5).startswith("[")]# Subtitle exports sometimes split one sung line into two cues; merge them back.merged = []for t, txt in lines: if merged and txt[:1].islower() and t - merged[-1][0] < 1.5: # a short cue continued by a lowercase one merged[-1] = (merged[-1][0], merged[-1][1] + " " + txt) else: merged.append((t, txt))
y, sr = sf.read(a.vocals); y = y.mean(1) if y.ndim > 1 else yhop = int(sr * 0.02); n = len(y) // hopdb = 20 * np.log10(np.sqrt((y[:n * hop].reshape(n, hop) ** 2).mean(1)) + 1e-9)on = db > np.percentile(db, 95) - 24def onset(t, win=0.9): """First frame of a sung phrase at or near t: a silent->voiced transition within ±win s, closest to t.""" lo, hi = int((t - win) / 0.02), int((t + win) / 0.02) cands = [i for i in range(max(lo, 1), min(hi, n)) if on[i] and not on[i - 1]] return min(cands, key=lambda i: abs(i * 0.02 - t)) * 0.02 if cands else tout = [dict(t=round(onset(t), 3), src=t, text=txt) for t, txt in merged]voiced = np.flatnonzero(on) * 0.02out.append(dict(t=round(float(voiced[-1]), 3), src=None, text="(last vocal)"))json.dump(out, open(OUT / "lyrics.json", "w"), indent=1, ensure_ascii=False)
d, dsr = librosa.load(a.drums, sr=22050, mono=True)tempo, beats = librosa.beat.beat_track(y=d, sr=dsr, units="time")json.dump([round(float(b), 3) for b in beats], open(OUT / "beats.json", "w"))print("tempo", float(np.atleast_1d(tempo)[0]), "beats", len(beats), "duration", round(len(y) / sr, 2))for o in out: print(f'{o["t"]:8.2f} (subtitle {o["src"] if o["src"] is None else round(o["src"], 2)}) {o["text"]}')