Spaces:
Running
Running
Download chartgen/timing.py from JacobLinCool/internal-model-p: direct link, hf CLI and curl.
- Browser
- Download file 9.56 kB
-
https://huggingface.co/spaces/JacobLinCool/internal-model-p/resolve/main/chartgen/timing.py
- Command line
-
hf download hf://spaces/JacobLinCool/internal-model-p/chartgen/timing.py
-
curl -L -o timing.py https://huggingface.co/spaces/JacobLinCool/internal-model-p/resolve/main/chartgen/timing.py
9.56 kB
| """Decode beat / downbeat activations (100 fps) into an osu!-style timing map. | |
| osu! timing is a list of sections (red lines): start time, beat length, meter. Charts are | |
| snapped to this grid to within ~1 ms (Stage 0), so the grid must be accurate to a few ms over | |
| the whole song: a 0.01% tempo error drifts ~12 ms over two minutes. The decoder therefore fits | |
| period and phase jointly over many beats instead of picking individual peaks. | |
| """ | |
| from __future__ import annotations | |
| import numpy as np | |
| FPS = 100.0 | |
| def _interp(act: np.ndarray, frames: np.ndarray) -> np.ndarray: | |
| f0 = np.floor(frames).astype(np.int64) | |
| w = frames - f0 | |
| ok = (f0 >= 0) & (f0 + 1 < len(act)) | |
| out = np.zeros(frames.shape, dtype=np.float64) | |
| f0c = np.clip(f0, 0, len(act) - 2) | |
| out[ok] = (act[f0c] * (1 - w) + act[f0c + 1] * w)[ok] | |
| return out | |
| def _score(act, t0_ms, t1_ms, periods_ms, phases_ms): | |
| """Mean activation at beats phase + k*period inside [t0, t1], for all (period, phase) pairs.""" | |
| P = periods_ms[:, None, None] | |
| ph = phases_ms[None, :, None] if phases_ms.ndim == 1 else phases_ms[:, :, None] | |
| kmax = int(np.ceil((t1_ms - t0_ms) / periods_ms.min())) + 1 | |
| k = np.arange(kmax)[None, None, :] | |
| t = t0_ms + ph + k * P | |
| valid = t <= t1_ms | |
| vals = _interp(act, t / 10.0) * valid | |
| return vals.sum(-1) / np.maximum(valid.sum(-1), 1) | |
| def fit_constant_tempo(act: np.ndarray, t0_ms: float, t1_ms: float, bpm_range=(60.0, 320.0), | |
| adjust_level: bool = True) -> tuple[float, float, float]: | |
| """Return (beat_length_ms, phase_ms relative to t0, score) for one constant-tempo stretch.""" | |
| seg = act[int(t0_ms / 10): int(t1_ms / 10) + 1].astype(np.float64) | |
| if len(seg) < 200: | |
| return 500.0, 0.0, 0.0 | |
| x = seg - seg.mean() | |
| ac = np.correlate(x, x, mode="full")[len(x) - 1:] | |
| lo, hi = int(60000 / bpm_range[1] / 10), int(60000 / bpm_range[0] / 10) | |
| lags = np.arange(lo, min(hi, len(ac) - 1)) | |
| cand = lags[np.argsort(ac[lags])[::-1][:6]] * 10.0 # ms | |
| best = (500.0, 0.0, -1.0) | |
| for c in cand: | |
| # stage 1: +/-3% in 0.05% steps, phase in 2 ms steps | |
| periods = c * (1 + np.arange(-0.03, 0.03, 0.0005)) | |
| phases = np.arange(0, c * 1.03, 2.0) | |
| sc = _score(act, t0_ms, t1_ms, periods, phases) | |
| i, j = np.unravel_index(np.argmax(sc), sc.shape) | |
| p1, f1 = periods[i], phases[j] | |
| # stage 2: +/-0.06% in 0.002% steps, phase +/-3 ms in 0.25 ms steps | |
| periods = p1 * (1 + np.arange(-0.0006, 0.0006, 0.00002)) | |
| phases = f1 + np.arange(-3, 3, 0.25) | |
| sc = _score(act, t0_ms, t1_ms, periods, phases) | |
| i, j = np.unravel_index(np.argmax(sc), sc.shape) | |
| if sc[i, j] > best[2]: | |
| best = (float(periods[i]), float(phases[j] % periods[i]), float(sc[i, j])) | |
| # beat level: prefer the fastest metrical level that still scores >= 80% of the best | |
| p, f, s = best | |
| for mult in ((0.5, 1 / 3) if adjust_level else ()): | |
| q = p * mult | |
| if 60000 / q > bpm_range[1]: | |
| continue | |
| sc = _score(act, t0_ms, t1_ms, np.array([q]), f + np.arange(-2, 2, 0.25)) | |
| if sc.max() >= 0.8 * s: | |
| j = int(np.argmax(sc)) | |
| p, f, s = q, float((f + np.arange(-2, 2, 0.25)[j]) % q), float(sc.max()) | |
| return p, f, s | |
| def _choose_meter(down: np.ndarray, beat_times: np.ndarray) -> tuple[int, int]: | |
| best = (4, 0, -1.0) | |
| vals = _interp(down, beat_times / 10.0) | |
| for m in (4, 3): | |
| for j in range(m): | |
| v = vals[j::m] | |
| sc = v.mean() if len(v) else 0.0 | |
| if sc > best[2] * (1.02 if m == 3 else 1.0): # mild preference for 4/4 | |
| best = (m, j, sc) | |
| return best[0], best[1] | |
| def decode_timing(beat_act: np.ndarray, down_act: np.ndarray, t0_ms: float, t1_ms: float, | |
| window_s: float = 24.0, change_tol: float = 0.01) -> np.ndarray: | |
| """Return sections [n, 5]: time_ms, beat_length_ms, meter, start_beat, omit_barline. | |
| Fits a global tempo, then local tempos on overlapping windows; consecutive windows whose | |
| tempo departs from the running segment by more than ``change_tol`` start a new segment. | |
| """ | |
| p, f, s = fit_constant_tempo(beat_act, t0_ms, t1_ms) | |
| # local tempo track | |
| bounds = [t0_ms] | |
| step = window_s * 500.0 | |
| local = [] | |
| t = t0_ms | |
| while t + window_s * 1000 <= t1_ms + step: | |
| a, b = t, min(t + window_s * 1000, t1_ms) | |
| if b - a >= 8000: | |
| lp, lf, ls = fit_constant_tempo(beat_act, a, b, bpm_range=(60000 / p / 1.6, 60000 / p * 2.2)) | |
| # express local tempo at the global beat level | |
| ratio = lp / p | |
| for r in (0.5, 2.0, 1 / 3, 3.0, 2 / 3, 1.5): | |
| if abs(ratio * r - 1) < abs(ratio - 1): | |
| ratio, lp = ratio * r, lp * r | |
| local.append((a, b, lp, ls)) | |
| t += step | |
| segs = [] | |
| cur = None | |
| for a, b, lp, ls in local: | |
| if cur is None: | |
| cur = [a, b, lp] | |
| elif abs(lp / cur[2] - 1) > change_tol: | |
| segs.append(cur) | |
| cur = [(a + b) / 2 - window_s * 250, b, lp] | |
| else: | |
| cur[1] = b | |
| if cur is not None: | |
| segs.append(cur) | |
| # refit each segment on its own span, searching only near its local tempo | |
| sections = [] | |
| if len(segs) <= 1: | |
| fits = [(t0_ms, t1_ms, p, f)] | |
| else: | |
| fits = [] | |
| for i, (a, b, lp) in enumerate(segs): | |
| a = t0_ms if i == 0 else a | |
| b = t1_ms if i == len(segs) - 1 else segs[i + 1][0] | |
| if b - a < 4000: | |
| continue | |
| sp, sf, _ = fit_constant_tempo(beat_act, a, b, bpm_range=(60000 / lp * 0.95, 60000 / lp * 1.05), adjust_level=False) | |
| fits.append((a, b, sp, sf)) | |
| for i, (a, b, sp, sf) in enumerate(fits): | |
| first = a + sf | |
| beats = first + np.arange(0, int((b - first) / sp) + 1) * sp | |
| m, j = _choose_meter(down_act, beats) | |
| start = first + j * sp | |
| if i == 0: # extend the first section back to the song start on whole bars | |
| start -= np.floor(start / (sp * m)) * sp * m | |
| sections.append([start, sp, m]) | |
| out = [] | |
| sb = 0.0 | |
| for i, (t, bl, m) in enumerate(sections): | |
| if i > 0: | |
| pt, pbl, _ = sections[i - 1] | |
| raw = sb + (t - pt) / pbl | |
| sb = float(round(raw)) if abs(raw - round(raw)) < 1e-3 else float(np.ceil(raw)) | |
| out.append([t, bl, m, sb, 0.0]) | |
| return np.array(out, dtype=np.float64) | |
| def beat_times(sections: np.ndarray, t0_ms: float, t1_ms: float) -> tuple[np.ndarray, np.ndarray]: | |
| """All beat and downbeat times of a section list within [t0, t1].""" | |
| beats, downs = [], [] | |
| for i, (t, bl, m, _, _) in enumerate(sections[:, :5] if sections.shape[1] >= 5 else np.c_[sections, np.zeros(len(sections))]): | |
| end = sections[i + 1, 0] if i + 1 < len(sections) else t1_ms | |
| k0 = int(np.ceil((max(t0_ms, -1e9) - t) / bl)) if t < t0_ms else 0 | |
| k1 = int(np.floor((end - t) / bl - 1e-9)) | |
| for k in range(k0, k1 + 1): | |
| tb = t + k * bl | |
| if t0_ms <= tb <= t1_ms and tb < end: | |
| beats.append(tb) | |
| if k % int(m) == 0: | |
| downs.append(tb) | |
| return np.array(beats), np.array(downs) | |
| def timing_metrics(pred_sections: np.ndarray, true_sections: np.ndarray, t0_ms: float, t1_ms: float) -> dict: | |
| """Compare a decoded timing map to the mapper's over the chart span.""" | |
| tb, td = beat_times(true_sections, t0_ms, t1_ms) | |
| pb, pd = beat_times(pred_sections, t0_ms - 2000, t1_ms + 2000) | |
| if len(tb) == 0 or len(pb) == 0: | |
| return {} | |
| idx = np.clip(np.searchsorted(pb, tb), 1, len(pb) - 1) | |
| err = np.minimum(np.abs(pb[idx] - tb), np.abs(pb[idx - 1] - tb)) | |
| main_true = true_sections[np.argmax(np.diff(np.r_[true_sections[:, 0], t1_ms]))] if len(true_sections) else None | |
| main_pred = pred_sections[np.argmax(np.diff(np.r_[pred_sections[:, 0], t1_ms]))] | |
| ratio = main_pred[1] / main_true[1] | |
| res = { | |
| "beat_err_median_ms": float(np.median(err)), | |
| "beat_within_5ms": float(np.mean(err <= 5)), | |
| "beat_within_10ms": float(np.mean(err <= 10)), | |
| "beat_within_20ms": float(np.mean(err <= 20)), | |
| "bpm_rel_err": float(abs(ratio - 1)), | |
| "bpm_level": "same" if abs(ratio - 1) < 0.01 else ("half" if abs(ratio - 2) < 0.02 else ("double" if abs(ratio - 0.5) < 0.01 else "other")), | |
| "n_sections_true": int(len(true_sections)), | |
| "n_sections_pred": int(len(pred_sections)), | |
| } | |
| if len(td) and len(pd): | |
| idx = np.clip(np.searchsorted(pd, td), 1, len(pd) - 1) | |
| derr = np.minimum(np.abs(pd[idx] - td), np.abs(pd[idx - 1] - td)) | |
| res["downbeat_within_20ms"] = float(np.mean(derr <= 20)) | |
| return res | |
| def tempo_class(sections: np.ndarray, t0_ms: float, t1_ms: float, tol: float = 0.002) -> str: | |
| """Classify a mapper timing map over [t0, t1]: 'constant', 'step' (a few sustained tempo | |
| changes) or 'gradual' (accelerando/ritardando or rapid alternation: four or more tempo | |
| changes within any 8 s, which only occurs when tempo is written beat by beat).""" | |
| s = sections[(sections[:, 0] < t1_ms)] | |
| if len(s) == 0: | |
| return "constant" | |
| keep = np.r_[True, np.abs(np.diff(np.log(s[:, 1]))) > tol] | |
| ch = s[keep][1:, 0] # times where the tempo really changes | |
| ch = ch[ch > t0_ms] | |
| if len(ch) == 0: | |
| return "constant" | |
| if len(ch) >= 4 and np.min(ch[3:] - ch[:-3]) < 8000: | |
| return "gradual" | |
| return "step" | |