Spaces:
Running
Running
Download chartgen/beattrack.py from JacobLinCool/internal-model-p: direct link, hf CLI and curl.
- Browser
- Download file 12.8 kB
-
https://huggingface.co/spaces/JacobLinCool/internal-model-p/resolve/main/chartgen/beattrack.py
- Command line
-
hf download hf://spaces/JacobLinCool/internal-model-p/chartgen/beattrack.py
-
curl -L -o beattrack.py https://huggingface.co/spaces/JacobLinCool/internal-model-p/resolve/main/chartgen/beattrack.py
12.8 kB
| """Beat-by-beat timing decoder for songs whose tempo changes often or continuously. | |
| ``timing.decode_timing`` fits constant tempos over long windows, which cannot follow an | |
| accelerando, a ritardando or quick alternation between tempos. This decoder instead tracks | |
| individual beats with dynamic programming over (beat time, interval to the previous beat), so | |
| the interval may drift a little at every beat or jump at a cost. The beat sequence is then | |
| written as osu! red lines the way mappers do it: runs of beats with a steady interval become one | |
| section fitted by least squares (sub-millisecond accuracy), and passages where the interval keeps | |
| changing get one red line per beat, with the bar line hidden on lines that are not bar starts. | |
| """ | |
| from __future__ import annotations | |
| import numpy as np | |
| from .timing import _choose_meter, _score, fit_constant_tempo | |
| RES_MS = 2.0 # DP time resolution | |
| MAX_BPM = 320.0 | |
| def _upsample(act: np.ndarray, t0_ms: float, t1_ms: float) -> tuple[np.ndarray, np.ndarray]: | |
| t = np.arange(t0_ms, t1_ms, RES_MS) | |
| return t, np.interp(t / 10.0, np.arange(len(act)), act.astype(np.float64)) | |
| def track_beats(beat_act: np.ndarray, t0_ms: float, t1_ms: float, period_ms: float, | |
| span: tuple[float, float] = (0.55, 1.8), jump_cost: float = 2.0, | |
| drift: int = 2, smooth: float = 400.0) -> np.ndarray: | |
| """Return beat times (ms). ``period_ms`` sets the beat level; intervals may range over | |
| ``span`` times it. Between consecutive beats the interval may change by up to ``drift`` | |
| grid steps (2 ms each) almost freely (cost ``smooth`` * (log ratio)^2), or jump anywhere for | |
| ``jump_cost`` plus a mild squared-log cost.""" | |
| t, a = _upsample(beat_act, t0_ms, t1_ms) | |
| r = a - a.mean() # zero expected reward for a beat placed at random | |
| min_tau = max(period_ms * span[0], 60000 / MAX_BPM) # charts essentially never exceed MAX_BPM | |
| taus = np.arange(int(min_tau / RES_MS), int(period_ms * span[1] / RES_MS) + 1) | |
| K, T = len(taus), len(t) | |
| logt = np.log(taus) | |
| S = np.full((T, K), -np.inf) | |
| back = np.full((T, K), -1, dtype=np.int64) | |
| first = int(period_ms * span[1] / RES_MS) + 1 | |
| S[:first] = r[:first, None] # a path may start anywhere in the first beat | |
| # banded transition (small drift) and global best (jump) per previous row | |
| d = np.arange(-drift, drift + 1) | |
| band_cost = smooth * (logt[:, None] - logt[np.clip(np.arange(K)[:, None] + d[None], 0, K - 1)]) ** 2 | |
| jump_pen = (logt[:, None] - logt[None, :]) ** 2 + jump_cost | |
| for i in range(first, T): | |
| prev = i - taus # row of the previous beat for each interval | |
| ok = prev >= 0 | |
| if not ok.any(): | |
| continue | |
| rows = S[np.where(ok, prev, 0)] # [K, K]: previous scores for every previous interval | |
| rows[~ok] = -np.inf | |
| cols = np.clip(np.arange(K)[:, None] + d[None], 0, K - 1) | |
| band = rows[np.arange(K)[:, None], cols] - band_cost | |
| bj = np.argmax(band, 1) | |
| best_band = band[np.arange(K), bj] | |
| jump = rows - jump_pen | |
| jj = np.argmax(jump, 1) | |
| best_jump = jump[np.arange(K), jj] | |
| use_jump = best_jump > best_band | |
| S[i] = r[i] + np.where(use_jump, best_jump, best_band) | |
| back[i] = np.where(use_jump, jj, cols[np.arange(K), bj]) | |
| # end anywhere in the last beat | |
| last = max(0, T - first) | |
| i, k = np.unravel_index(np.argmax(S[last:]), S[last:].shape) | |
| i += last | |
| beats = [] | |
| while i >= 0 and k >= 0: | |
| beats.append(i) | |
| pk = back[i, k] | |
| i, k = i - taus[k], pk | |
| if pk < 0: | |
| break | |
| idx = np.array(beats[::-1]) | |
| idx = idx[idx >= 0] | |
| # sub-grid refinement: parabolic peak of the activation within +/-6 ms | |
| out = [] | |
| for j in idx: | |
| lo, hi = max(0, j - 3), min(T, j + 4) | |
| m = lo + int(np.argmax(a[lo:hi])) | |
| if 0 < m < T - 1: | |
| y0, y1, y2 = a[m - 1], a[m], a[m + 1] | |
| den = y0 - 2 * y1 + y2 | |
| off = 0.5 * (y0 - y2) / den if den < 0 else 0.0 | |
| out.append(t[m] + np.clip(off, -1, 1) * RES_MS) | |
| else: | |
| out.append(t[m]) | |
| return np.array(out) | |
| def beats_to_sections(beats: np.ndarray, down_act: np.ndarray, tol_ms: float = 4.0, | |
| min_run: int = 8) -> np.ndarray: | |
| """Convert beat times into sections [n, 5] (time, beat_length, meter, start_beat, omit).""" | |
| n = len(beats) | |
| if n < 2: | |
| return np.array([[beats[0] if n else 0.0, 500.0, 4, 0.0, 0.0]]) | |
| # greedy runs of steady interval (linear fit of time on beat index within tol) | |
| runs = [] | |
| i = 0 | |
| while i < n - 1: | |
| j = i + 2 | |
| best = None | |
| while j <= n: | |
| k = np.arange(i, j) | |
| A = np.c_[np.ones(len(k)), k - i] | |
| coef, *_ = np.linalg.lstsq(A, beats[i:j], rcond=None) | |
| res = np.abs(A @ coef - beats[i:j]) | |
| # robust: tolerate isolated misplaced beats, but never a drift beyond 2.5 tol | |
| if np.percentile(res, 90) > tol_ms or res.max() > 2.5 * tol_ms: | |
| break | |
| best = (j, coef) | |
| j += 1 | |
| j, coef = best | |
| # trim trailing beats the robust fit tolerated but that already belong to the next tempo | |
| while j - i > 2: | |
| k = np.arange(i, j) | |
| A = np.c_[np.ones(len(k)), k - i] | |
| coef, *_ = np.linalg.lstsq(A, beats[i:j], rcond=None) | |
| if abs(A[-1] @ coef - beats[j - 1]) <= tol_ms: | |
| break | |
| j -= 1 | |
| runs.append((i, j, coef)) # beats i..j-1 follow t = coef0 + coef1*(idx-i) | |
| i = j - 1 if j - i >= min_run else i + 1 | |
| if i >= n - 1: | |
| break | |
| meter, phase = _choose_meter(down_act, beats) | |
| bar_of = (np.arange(n) - phase) % meter # position of each beat in its bar | |
| sections = [] # (time, beat_length, meter, omit) per starting beat index | |
| covered = 0 | |
| for (i0, j, coef) in runs: | |
| if j - i0 < min_run: | |
| continue | |
| i = max(i0, covered) | |
| # per-beat lines up to the first bar start, then one steady section | |
| first_bar = next((b for b in range(i, j) if bar_of[b] == 0), i) | |
| for b in range(covered, first_bar): | |
| sections.append((b, beats[b], beats[b + 1] - beats[b], bar_of[b] != 0)) | |
| sections.append((first_bar, coef[0] + coef[1] * (first_bar - i0), coef[1], bar_of[first_bar] != 0)) | |
| covered = j - 1 | |
| for b in range(covered, n - 1): | |
| if not sections or b > sections[-1][0]: | |
| sections.append((b, beats[b], beats[b + 1] - beats[b], bar_of[b] != 0)) | |
| sections.sort(key=lambda s: s[0]) | |
| out = [] | |
| for bi, t, bl, omit in sections: | |
| if out: | |
| pt, pbl, _, pbi, _ = out[-1] | |
| # same tempo and continuous phase: the previous line already covers this one | |
| if abs(bl / pbl - 1) < 0.002 and abs(pt + (bi - pbi) * pbl - t) < 2.0 and (bi - pbi) % meter == 0: | |
| continue | |
| out.append([t, bl, meter, float(bi), float(omit)]) | |
| return np.array(out, dtype=np.float64) | |
| def decode_timing_dp(beat_act: np.ndarray, down_act: np.ndarray, t0_ms: float, t1_ms: float) -> np.ndarray: | |
| p, _, _ = fit_constant_tempo(beat_act, t0_ms, t1_ms) | |
| beats = track_beats(beat_act, t0_ms, t1_ms, p) | |
| # beat level check: if the points halfway between tracked beats are as strong as the beats, | |
| # the tracker is running at half the beat rate somewhere; track again at the faster level | |
| if len(beats) > 8: | |
| mids = (beats[1:] + beats[:-1]) / 2 | |
| on = np.interp(beats / 10.0, np.arange(len(beat_act)), beat_act.astype(np.float64)) | |
| mid = np.interp(mids / 10.0, np.arange(len(beat_act)), beat_act.astype(np.float64)) | |
| if np.mean(mid > 0.5 * np.median(on)) > 0.25 and 60000 / (p / 2) <= MAX_BPM: | |
| beats = track_beats(beat_act, t0_ms, t1_ms, p / 2) | |
| return beats_to_sections(beats, down_act) | |
| def _smooth_beats(beats: np.ndarray, half: int = 3) -> np.ndarray: | |
| """Local quadratic fit of beat time on beat index (+/- half beats) to remove frame jitter.""" | |
| out = beats.copy() | |
| n = len(beats) | |
| for i in range(n): | |
| lo, hi = max(0, i - half), min(n, i + half + 1) | |
| iv = np.diff(beats[lo:hi]) | |
| if hi - lo >= 4 and iv.max() / iv.min() < 1.1: # never smooth across a tempo jump | |
| k = np.arange(lo, hi) - i | |
| out[i] = np.polyval(np.polyfit(k, beats[lo:hi], 2), 0) | |
| return out | |
| def decode_timing_hybrid(beat_act: np.ndarray, down_act: np.ndarray, t0_ms: float, t1_ms: float, | |
| steady_tol: float = 0.015, min_steady: int = 8) -> np.ndarray: | |
| """Beat tracking for the tempo structure, then a precise constant-tempo fit on every | |
| steady stretch; one smoothed red line per beat only where the tempo keeps changing.""" | |
| p, _, _ = fit_constant_tempo(beat_act, t0_ms, t1_ms) | |
| beats = track_beats(beat_act, t0_ms, t1_ms, p) | |
| if len(beats) > 8: | |
| mids = (beats[1:] + beats[:-1]) / 2 | |
| on = np.interp(beats / 10.0, np.arange(len(beat_act)), beat_act.astype(np.float64)) | |
| mid = np.interp(mids / 10.0, np.arange(len(beat_act)), beat_act.astype(np.float64)) | |
| if np.mean(mid > 0.5 * np.median(on)) > 0.25 and 60000 / (p / 2) <= MAX_BPM: | |
| beats = track_beats(beat_act, t0_ms, t1_ms, p / 2) | |
| n = len(beats) | |
| if n < min_steady: | |
| return decode_timing_dp(beat_act, down_act, t0_ms, t1_ms) | |
| iv = np.diff(beats) | |
| loc = np.array([np.median(iv[max(0, i - 4): i + 5]) for i in range(len(iv))]) # local interval per gap | |
| # steady regions: maximal runs of gaps whose local interval stays within tol of the run median | |
| regions = [] | |
| i = 0 | |
| while i < len(loc): | |
| j = i + 1 | |
| while j < len(loc) and abs(loc[j] / np.median(loc[i:j + 1]) - 1) < steady_tol: | |
| j += 1 | |
| if j - i >= min_steady: | |
| regions.append((i, j)) # beats i..j (gaps i..j-1) | |
| i = j | |
| else: | |
| i += 1 | |
| meter, phase = _choose_meter(down_act, beats) | |
| bar_of = (np.arange(n) - phase) % meter | |
| smooth = _smooth_beats(beats) | |
| lines = [] # (beat_idx, time, beat_length, omit) | |
| covered = 0 | |
| for a, b in regions: | |
| first_bar = next((k for k in range(max(a, covered), b) if bar_of[k] == 0), max(a, covered)) | |
| for k in range(covered, first_bar): | |
| lines.append((k, smooth[k], smooth[k + 1] - smooth[k], bar_of[k] != 0)) | |
| # precise fit on this stretch: least squares on the tracked beats (edges trimmed, since | |
| # the local interval lags a tempo change by a few beats), then a narrow template search | |
| lo, hi = min(a + 4, first_bar), b - 4 if b - 4 > a + 8 else b | |
| k = np.arange(lo, hi + 1) | |
| coef = np.polyfit(k - first_bar, beats[lo:hi + 1], 1) # time at first_bar, period | |
| res = beats[lo:hi + 1] - np.polyval(coef, k - first_bar) | |
| good = np.abs(res) < 3 * max(np.median(np.abs(res)), 1.0) | |
| coef = np.polyfit((k - first_bar)[good], beats[lo:hi + 1][good], 1) | |
| start, sp = float(coef[1]), float(coef[0]) | |
| periods = sp * (1 + np.arange(-0.001, 0.001, 0.00005)) | |
| phases = np.arange(-4, 4, 0.25) | |
| t_lo = start - (first_bar - a) * sp | |
| sc = _score(beat_act, t_lo, beats[b], periods, (start - t_lo) % sp + phases) | |
| pi, fi = np.unravel_index(np.argmax(sc), sc.shape) | |
| sp = float(periods[pi]) | |
| start = float(start + phases[fi]) | |
| lines.append((first_bar, start, sp, bar_of[first_bar] != 0)) | |
| covered = b | |
| for k in range(covered, n - 1): | |
| lines.append((k, smooth[k], smooth[k + 1] - smooth[k], bar_of[k] != 0)) | |
| out = [] | |
| for bi, t, bl, omit in lines: | |
| out.append([t, bl, meter, float(bi), float(omit)]) | |
| return np.array(out, dtype=np.float64) | |
| def grid_score(beat_act: np.ndarray, sections: np.ndarray, t0_ms: float, t1_ms: float) -> float: | |
| from .timing import beat_times | |
| b, _ = beat_times(sections, t0_ms, t1_ms) | |
| if len(b) == 0: | |
| return 0.0 | |
| return float(np.interp(b / 10.0, np.arange(len(beat_act)), beat_act.astype(np.float64)).mean()) | |
| def decode_timing_auto(beat_act: np.ndarray, down_act: np.ndarray, t0_ms: float, t1_ms: float, | |
| margin: float = 0.05) -> np.ndarray: | |
| """Use the simple windowed constant-tempo map unless the beat-tracked hybrid map explains the | |
| beat activations clearly better (songs whose tempo really changes).""" | |
| from .timing import decode_timing | |
| simple = decode_timing(beat_act, down_act, t0_ms, t1_ms) | |
| hybrid = decode_timing_hybrid(beat_act, down_act, t0_ms, t1_ms) | |
| s0, s1 = grid_score(beat_act, simple, t0_ms, t1_ms), grid_score(beat_act, hybrid, t0_ms, t1_ms) | |
| return hybrid if s1 > s0 * (1 + margin) else simple | |