JacobLinCool's picture
Release Model P chart generation demo for osu!taiko and TJA
2469e25 verified
Raw History Blame Contribute Delete
10.8 kB
"""Whole-song inference: audio -> timing map -> notes + SV + kiai -> .osu file."""
from __future__ import annotations
import argparse
from dataclasses import dataclass
from pathlib import Path
import numpy as np
import torch
from .dataset import WINDOW, make_example
from .features import decode_audio, log_mel
from .generate import generate
from .model import B0, B0Config
from .timing import beat_times, decode_timing
TIER_NAMES = ["Kantan", "Futsuu", "Muzukashii", "Oni", "Inner Oni"]
TIER_OD = [4.0, 5.0, 5.5, 6.0, 6.5]
@dataclass
class GeneratedChart:
sections: np.ndarray # [n, 5] time, beat_length, meter, start_beat, omit_barline
kiai: list[tuple[float, float]]
time: np.ndarray # ms
type: np.ndarray
length_beats: np.ndarray
sv: np.ndarray
tier: int
def load_model(path: str | Path, device) -> B0:
ck = torch.load(path, map_location=device, weights_only=False)
cfg = B0Config(**ck["config"])
model = B0(cfg).to(device)
model.load_state_dict(ck["model"])
model.eval()
return model
def _windows(n_frames: int, hop: int):
starts = list(range(0, max(1, n_frames - WINDOW // 2), hop))
return starts
def _dummy_chart(sections: np.ndarray, tier: int) -> dict:
"""A chart with timing only (one far-away note) so make_example can build grid inputs."""
far = 1e9
return {"tier": tier, "sections": sections, "time": np.array([far]), "beat": np.array([1e7]),
"type": np.zeros(1, np.int8), "length_beats": np.zeros(1, np.float32),
"delta_ms": np.zeros(1, np.float32), "sv": np.ones(1, np.float32), "kiai": np.zeros((0, 2))}
@torch.no_grad()
def frame_activations(model: B0, mel: np.ndarray, device, sections: np.ndarray | None = None, tier: int = 3):
"""Average sigmoid outputs over 50%-overlapping windows. Returns beat, downbeat, kiai (kiai needs sections)."""
n = len(mel)
acc = np.zeros((n, 3))
cnt = np.zeros(n)
song = {"mel": mel}
chart = _dummy_chart(sections if sections is not None else np.array([[0.0, 500.0, 4, 0, 0]]), tier)
starts = _windows(n, WINDOW // 2)
for i in range(0, len(starts), 16):
exs = [make_example(song, chart, s) for s in starts[i:i + 16]]
mel_b = torch.from_numpy(np.stack([e.mel for e in exs])).to(device)
bf = torch.from_numpy(np.stack([e.beat_feat for e in exs])).to(device)
hi, mem = model.encode(mel_b)
tl = torch.sigmoid(model.timing_logits(hi, mem).float()).cpu().numpy()
kl = torch.sigmoid(model.kiai_logits(hi, model.with_grid(mem, bf)).float()).cpu().numpy()
for e, s, t, k in zip(exs, starts[i:i + 16], tl, kl):
m = min(WINDOW, n - s)
acc[s:s + m, :2] += t[:m]
acc[s:s + m, 2] += k[:m]
cnt[s:s + m] += 1
acc /= np.maximum(cnt, 1)[:, None]
return acc[:, 0], acc[:, 1], acc[:, 2]
def music_span(mel: np.ndarray) -> tuple[float, float]:
energy = mel.astype(np.float32).mean(1)
loud = np.where(energy > np.percentile(energy, 20))[0]
return (loud[0] * 10.0, loud[-1] * 10.0) if len(loud) else (0.0, len(mel) * 10.0)
def predict_timing(model: B0, mel: np.ndarray, device, t0: float | None = None, t1: float | None = None) -> np.ndarray:
beat_p, down_p, _ = frame_activations(model, mel, device)
if t0 is None or t1 is None:
t0, t1 = music_span(mel)
return decode_timing(beat_p, down_p, t0, t1)
def decode_kiai(kiai_p: np.ndarray, sections: np.ndarray, t0: float, t1: float, min_bars: int = 4, max_gap_bars: int = 2,
thr: float = 0.5):
"""Kiai intervals: a measure is on when its mean kiai probability is above thr (0.5 before stage 4b; stage 4b
calibrates thr per tier on tune songs), short gaps are filled, short runs dropped."""
_, downs = beat_times(sections, t0, t1)
downs = np.r_[downs, t1]
if len(downs) < 2:
return []
def bar_on(a, b):
seg = kiai_p[int(a / 10):max(int(a / 10) + 1, int(b / 10))]
return len(seg) > 0 and seg.mean() > thr
on = np.array([bar_on(a, b) for a, b in zip(downs[:-1], downs[1:])])
# fill short gaps, then drop short runs
runs = []
i = 0
while i < len(on):
if on[i]:
j = i
while j < len(on) and on[j]:
j += 1
runs.append([i, j])
i = j
else:
i += 1
merged = []
for r in runs:
if merged and r[0] - merged[-1][1] <= max_gap_bars:
merged[-1][1] = r[1]
else:
merged.append(r)
return [(float(downs[a]), float(downs[b])) for a, b in merged if b - a >= min_bars]
@torch.no_grad()
def generate_chart(model: B0, mel: np.ndarray, tier: int, device, sections: np.ndarray | None = None,
temperature: float = 0.0) -> GeneratedChart:
n_ms = len(mel) * 10.0
# timing span: where the music is (skip leading/trailing silence)
t0, t1 = music_span(mel)
if sections is None:
sections = predict_timing(model, mel, device, t0, t1)
_, _, kiai_p = frame_activations(model, mel, device, sections, tier)
chart = _dummy_chart(sections, tier)
song = {"mel": mel}
starts = list(range(int(t0 // 10), int(t1 // 10), WINDOW))
times, types, lens, svs = [], [], [], []
for i in range(0, len(starts), 32):
exs = [make_example(song, chart, s) for s in starts[i:i + 32]]
preds = generate(model, exs, device, temperature=temperature)
for e, p in zip(exs, preds):
t = p["time"] + e.start_ms
keep = t < e.start_ms + WINDOW * 10.0
times.append(t[keep]); types.append(p["type"][keep]); lens.append(p["length"][keep]); svs.append(p["sv"][keep])
time = np.concatenate(times) if times else np.zeros(0)
order = np.argsort(time)
time = time[order]
keep = np.r_[True, np.diff(time) > 1.0] # drop duplicates across window seams
first_note, last_note = (time[0], time[-1]) if len(time) else (t0, t1)
kiai = decode_kiai(kiai_p, sections, first_note, last_note)
return GeneratedChart(sections=sections, kiai=kiai, time=time[keep],
type=np.concatenate(types)[order][keep] if types else np.zeros(0, int),
length_beats=np.concatenate(lens)[order][keep] if lens else np.zeros(0),
sv=np.concatenate(svs)[order][keep] if svs else np.zeros(0), tier=tier)
def to_osu(c: GeneratedChart, audio_filename: str, title: str = "Unknown", artist: str = "Unknown",
slider_multiplier: float = 1.4) -> str:
"""Write a playable osu!taiko file (format v14)."""
secs = c.sections
def section_at(t):
i = max(int(np.searchsorted(secs[:, 0], t, side="right")) - 1, 0)
return secs[i]
def in_kiai(t):
return any(a <= t < b for a, b in c.kiai)
# timing points: red lines, then green lines where SV or kiai changes
events = [] # (time, is_red, beat_length or sv, meter, kiai, omit)
for s in secs:
events.append((float(s[0]), True, float(s[1]), int(s[2]), in_kiai(s[0]), bool(s[4])))
changes = sorted({t for a, b in c.kiai for t in (a, b)} | {float(t) for t in c.time})
cur_sv, cur_kiai = 1.0, False
red_times = set(float(s[0]) for s in secs)
for t in changes:
idx = np.searchsorted(c.time, t)
sv = float(c.sv[idx]) if idx < len(c.time) and abs(c.time[idx] - t) < 1e-6 else cur_sv
k = in_kiai(t)
last_red = max((rt for rt in red_times if rt <= t), default=None)
if last_red is not None and abs(last_red - t) < 1e-6:
cur_sv, cur_kiai = 1.0, k
if abs(sv - cur_sv) > 1e-3 or k != cur_kiai:
events.append((t, False, sv, int(section_at(t)[2]), k, False))
cur_sv, cur_kiai = sv, k
events.sort(key=lambda e: (e[0], not e[1]))
tp_lines = []
for t, red, v, m, k, omit in events:
eff = (1 if k else 0) | (8 if (red and omit) else 0)
if red:
tp_lines.append(f"{t:.3f},{v:.12g},{m},1,0,100,1,{eff}")
else:
tp_lines.append(f"{t:.3f},{-100.0 / v:.12g},{m},1,0,100,0,{eff}")
ho = []
for i, (t, ty, lb, sv) in enumerate(zip(c.time, c.type, c.length_beats, c.sv)):
ti = int(round(t))
if ty in (0, 1, 2, 3):
hs = (8 if ty in (1, 3) else 0) | (4 if ty in (2, 3) else 0)
ho.append(f"256,192,{ti},1,{hs},0:0:0:0:")
else:
bl = float(section_at(t)[1])
lb = max(lb, 0.25)
if i + 1 < len(c.time): # do not run into the next note
lb = min(lb, max(0.25, (c.time[i + 1] - t) / bl - 0.25))
if ty in (4, 5):
px = lb * slider_multiplier * 100.0 * sv
ho.append(f"256,192,{ti},2,{4 if ty == 5 else 0},L|{256 + int(px)}:192,1,{px:.4f}")
else:
ho.append(f"256,192,{ti},12,0,{int(round(t + lb * bl))},0:0:0:0:")
name = TIER_NAMES[c.tier]
return "\n".join([
"osu file format v14", "",
"[General]", f"AudioFilename: {audio_filename}", "AudioLeadIn: 0", "PreviewTime: -1", "Countdown: 0",
"SampleSet: Normal", "StackLeniency: 0.7", "Mode: 1", "LetterboxInBreaks: 0", "WidescreenStoryboard: 0", "",
"[Editor]", "BeatDivisor: 4", "",
"[Metadata]", f"Title:{title}", f"TitleUnicode:{title}", f"Artist:{artist}", f"ArtistUnicode:{artist}",
"Creator:chartgen", f"Version:{name}", "Source:", "Tags:generated", "BeatmapID:0", "BeatmapSetID:-1", "",
"[Difficulty]", "HPDrainRate:5", "CircleSize:5", f"OverallDifficulty:{TIER_OD[c.tier]}", "ApproachRate:5",
f"SliderMultiplier:{slider_multiplier}", "SliderTickRate:1", "",
"[Events]", "//Background and Video events", "",
"[TimingPoints]", *tp_lines, "",
"[HitObjects]", *ho, "",
])
def main(argv=None):
p = argparse.ArgumentParser(description="Generate an osu!taiko chart from audio")
p.add_argument("audio", type=Path)
p.add_argument("--model", type=Path, required=True)
p.add_argument("--tier", type=int, default=3, help="0 Kantan .. 4 Inner Oni")
p.add_argument("--out", type=Path)
p.add_argument("--title", default=None)
p.add_argument("--artist", default="Unknown")
a = p.parse_args(argv)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = load_model(a.model, device)
mel = log_mel(decode_audio(str(a.audio)), device=str(device))
c = generate_chart(model, mel, a.tier, device)
out = a.out or a.audio.with_suffix(f".{TIER_NAMES[a.tier].replace(' ', '')}.osu")
out.write_text(to_osu(c, a.audio.name, a.title or a.audio.stem, a.artist))
print(out, f"{len(c.time)} notes, {len(c.sections)} timing sections, {len(c.kiai)} kiai")
if __name__ == "__main__":
main()