File size: 11,803 Bytes
2469e25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
"""Infer a paired Model P chartset and export it for osu!taiko and TJA."""
from __future__ import annotations

import argparse
from dataclasses import replace
from functools import lru_cache
import hashlib
import json
import math
import os
from pathlib import Path
import subprocess
from types import SimpleNamespace
import zipfile

from huggingface_hub import hf_hub_download
import numpy as np
from safetensors.torch import load_file
import torch

from chartgen.beattrack import decode_timing_auto
from chartgen.dataset import GRID, MAX_AHEAD, WINDOW, bar_plan, make_example, measure_at
from chartgen.features import SAMPLE_RATE, decode_audio, log_mel
from chartgen.gen_mapset import window_plan
from chartgen.generate import generate
from chartgen.infer import GeneratedChart, _dummy_chart, frame_activations, music_span, to_osu
from chartgen.model import B0, B0Config
from chartgen.rhythm_eval2 import beats_tol
from chartgen.v11 import pmap
from chartgen.v11.rmap import RMap, predict_group
from chartgen.v11.rmap_data import Group, beat_table
from chartgen.v11.rmap_eval import apply_calib, load_calib
from chartgen.v11.s2_arms import pseudo_chart
from chartgen.v11.s5d_osz import hold_rolls, shared_kiai
from chartgen.v11.song_signature import song_onsets
from tja_export import to_tja

ROOT = Path(__file__).resolve().parent
MODEL_REPO = "JacobLinCool/internal-model-p"
MODEL_REVISION = "f7752e9a48baa7adf7bd43ba63eaadbc522219b9"
DEVICE = torch.device("cpu")
FLOORS = {"3": 57.0, "4": 32.0}
TIERS = {3: "Oni", 4: "Inner Oni"}
SYNTH_SONG_ID = 990000000
AUDIO_NAME = "audio.mp3"
MAX_SECONDS = 180
MIN_SECONDS = 8
COLOUR_WINDOW_NOTES = 360


class AudioInputError(ValueError):
    """Input that the public demo cannot decode or use."""


class EighthGate:
    def __init__(self, path):
        self.theta = json.loads(path.read_text(encoding="utf-8"))

    def gate(self, tier, share):
        return share >= self.theta[str(tier)]


@lru_cache(maxsize=1)
def load_models():
    local = os.environ.get("MODEL_P_DIR")

    def asset(name):
        if local:
            return Path(local) / name
        return Path(hf_hub_download(MODEL_REPO, name, revision=MODEL_REVISION))

    manifest = json.loads(asset("config.json").read_text(encoding="utf-8"))
    models = {
        "p": pmap.PMap(**manifest["p"]["config"]),
        "r": RMap(**manifest["r"]["config"]),
        "b9fix": B0(B0Config(**manifest["b9fix"]["config"])),
    }
    for name, model in models.items():
        entry = manifest[name]
        path = asset(entry["filename"])
        with path.open("rb") as file:
            digest = hashlib.file_digest(file, "sha256").hexdigest()
        if digest != entry["sha256"]:
            raise RuntimeError(f"Checkpoint hash mismatch for {name}.")
        model.load_state_dict(load_file(path), strict=True)
        model.eval()
    return models


def transcode(input_path, output_path):
    # Share one exported, decoder-compatible audio file between both formats.
    result = subprocess.run(
        ["ffmpeg", "-nostdin", "-v", "error", "-y", "-i", os.fspath(input_path),
         "-map", "0:a:0", "-t", str(MAX_SECONDS + 1), "-c:a", "libmp3lame", "-q:a", "2",
         "-ac", "2", "-ar", "44100", os.fspath(output_path)],
        capture_output=True, timeout=45, check=False,
    )
    if result.returncode:
        raise AudioInputError("Upload a readable file with an audio track.")
    samples = decode_audio(os.fspath(output_path))
    if not MIN_SECONDS * SAMPLE_RATE <= len(samples) <= MAX_SECONDS * SAMPLE_RATE:
        raise AudioInputError(f"Audio must be {MIN_SECONDS} to {MAX_SECONDS} seconds long.")
    if not np.isfinite(samples).all() or np.sqrt(np.mean(samples ** 2)) < 1e-4:
        raise AudioInputError("The uploaded audio is silent.")
    return samples


def make_sections(b9, mel, bpm, downbeat_ms):
    start_ms, end_ms = music_span(mel)
    if end_ms - start_ms < 2500:
        raise AudioInputError("The file needs at least 2.5 seconds of active audio.")
    if bpm is None:
        beat, downbeat, _ = frame_activations(b9, mel, DEVICE)
        sections = decode_timing_auto(beat, downbeat, start_ms, end_ms)
    else:
        if not math.isfinite(bpm) or not 60 <= bpm <= 320:
            raise AudioInputError("Set BPM between 60 and 320.")
        if not math.isfinite(downbeat_ms) or not 0 <= downbeat_ms < len(mel) * 10:
            raise AudioInputError("The first downbeat must fall inside the audio.")
        sections = np.array([[downbeat_ms, 60000 / bpm, 4, 0, 0]], dtype=np.float64)

    # Extend the first timing section by whole measures to cover any pickup.
    sections = np.asarray(sections, dtype=np.float64).copy()
    bar_ms = sections[0, 1] * sections[0, 2]
    lead_bars = max(0, math.ceil(sections[0, 0] / bar_ms))
    sections[0, 0] -= lead_bars * bar_ms
    sections[0, 3] -= lead_bars * sections[0, 2]
    return sections, max(0.0, start_ms - 2000.0), end_ms


@torch.inference_mode()
def colour_notes(b9, mel, sections, tier, times, seed):
    """Run the original forced-position note decoder and retain P's timing lattice."""
    grid = np.rint(beats_tol(sections, times) * GRID).astype(np.int64)
    if np.any(np.diff(grid) <= 0):
        raise RuntimeError("Model P emitted non-increasing grid positions.")
    song = {"mel": mel}
    template = _dummy_chart(sections, tier)
    target = pseudo_chart(grid, sections, tier)
    bars = measure_at(sections, grid / GRID)
    first_bar = int(bars[0])
    plan = bar_plan(grid, np.zeros(len(grid), np.int64), first_bar, sections, None, int(bars[-1]) - first_bar + 1)
    type_bias = np.zeros(7, np.float32)
    type_bias[4:] = -1e9
    colours, speeds = [], []
    breaks = set((np.flatnonzero(np.diff(grid // GRID) > MAX_AHEAD) + 1).tolist())
    start = 0
    while start < len(grid):
        frame = max(0, int(times[start] // 10))
        ex = make_example(song, template, frame)
        stop = min(start + COLOUR_WINDOW_NOTES, np.searchsorted(times, (frame + WINDOW) * 10))
        for boundary in range(start + 1, stop):
            if boundary in breaks:
                stop = boundary
                break
        stop = min(stop, np.searchsorted(grid, ex.start_grid + len(ex.grid_time) - 1))
        offsets = grid[start:stop] - ex.start_grid
        if not len(offsets) or offsets[0] <= 0:
            raise RuntimeError("A Model P note fell outside its colour decoder window.")
        hint = make_example(song, target, frame)
        ex = replace(ex, plan_rho=hint.plan_rho, plan_r=hint.plan_r, plan_gap=hint.plan_gap)
        window, _, _ = window_plan(plan, first_bar, sections, frame)
        allowed = np.zeros(len(ex.grid_time) + 1, bool)
        allowed[offsets] = True
        torch.manual_seed(seed + frame)
        pred = generate(
            b9, [ex], DEVICE, temperature=0.9, plan_source="oracle", bar_plan=window[None],
            allowed=[allowed], required=[offsets], continue_until=[int(offsets[-1])], type_bias=type_bias,
        )[0]
        if not np.array_equal(pred["grid_offset"], offsets) or np.any(pred["type"] > 3):
            raise RuntimeError("The colour decoder changed Model P's hit positions.")
        colours.append(pred["type"])
        speeds.append(pred["sv"])
        start = stop
    return np.concatenate(colours), np.concatenate(speeds)


@torch.inference_mode()
def infer(samples, seed=0, bpm=None, downbeat_ms=0.0):
    models = load_models()
    mel = log_mel(samples).astype(np.float32)
    b9 = models["b9fix"]
    sections, start, end = make_sections(b9, mel, bpm, downbeat_ms)
    table = beat_table(sections, len(mel))
    group = Group(SYNTH_SONG_ID, "upload", "new", 3, table, sections, song_index=0)
    song = {"mel": mel, "beatmapset_id": SYNTH_SONG_ID}
    corpus = SimpleNamespace(groups=[group], songs=[song], ons=[song_onsets(mel)])
    lg = predict_group(models["r"], corpus, 0, DEVICE)
    calib = load_calib(ROOT / "assets/r-calibration.json")
    gate = EighthGate(ROOT / "assets/eighth-gate.json")
    result = pmap.gen_song(
        models["p"], corpus, 0, song, apply_calib(lg, calib), gate, FLOORS,
        seed, 1, DEVICE, span=(start, end),
    )[0]
    _, _, kiai_prob = frame_activations(b9, mel, DEVICE, sections, 4)
    candidates = [c for c in result["charts"].values() if len(c["time"]) >= 2]
    if not candidates or any(not len(c["time"]) for c in result["charts"].values()):
        raise AudioInputError("The model found too few notes. Try a more rhythmic track or set its BPM and downbeat.")
    kiai = shared_kiai(kiai_prob, sections, result["charts"])
    charts = {}
    for tier, chart in result["charts"].items():
        hits = chart["time"]
        types, sv = colour_notes(b9, mel, sections, tier, hits, seed + 1000 * tier)
        rolls, lengths = hold_rolls(result["p"][tier]["tok"], table, pmap.tables()["HOLD"])
        roll_section = np.searchsorted(sections[:, 0], rolls, side="right") - 1
        next_hit = np.searchsorted(hits, rolls, side="right")
        hit_end = np.r_[hits, len(samples) * 1000 / SAMPLE_RATE][next_hit]
        beat_ms = sections[roll_section, 1]
        lengths = np.minimum(lengths, (hit_end - rolls) / beat_ms - 0.25)
        valid = (lengths >= 0.25) & (rolls < len(samples) * 1000 / SAMPLE_RATE)
        times = np.concatenate([hits, rolls[valid]])
        order = np.argsort(times, kind="stable")
        charts[tier] = GeneratedChart(
            sections=sections, kiai=kiai, time=times[order],
            type=np.r_[types, np.full(int(valid.sum()), 4)][order],
            length_beats=np.r_[np.zeros(len(hits)), lengths[valid]][order],
            sv=np.r_[sv, np.ones(int(valid.sum()))][order], tier=tier,
        )
    return charts


def clean_field(value):
    return " ".join(str(value).splitlines()).replace("//", "/").strip()[:120]


def generate_package(input_path, output, *, title, artist="", seed=0, bpm=None, downbeat_ms=0.0):
    if isinstance(seed, bool) or seed != int(seed) or not 0 <= seed < 2 ** 31:
        raise AudioInputError("Seed must be an integer from 0 to 2147483647.")
    output.mkdir(parents=True, exist_ok=True)
    audio = output / AUDIO_NAME
    samples = transcode(input_path, audio)
    charts = infer(samples, int(seed), bpm, downbeat_ms)
    title = clean_field(title) or "Generated taiko chart"
    artist = clean_field(artist)
    osz = output / "Model P.osz"
    with zipfile.ZipFile(osz, "w", zipfile.ZIP_DEFLATED) as package:
        package.write(audio, AUDIO_NAME)
        for tier, chart in charts.items():
            package.writestr(f"{TIERS[tier]}.osu", to_osu(chart, AUDIO_NAME, title, artist))
    tja = output / "Model P TJA.zip"
    with zipfile.ZipFile(tja, "w", zipfile.ZIP_DEFLATED) as package:
        package.write(audio, AUDIO_NAME)
        package.writestr("Model P.tja", to_tja(charts, AUDIO_NAME, title, artist))
    audio.unlink()
    return osz, tja, {TIERS[tier]: int((chart.type <= 3).sum()) for tier, chart in sorted(charts.items())}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("audio", type=Path)
    parser.add_argument("--output", type=Path, default=Path("export"))
    parser.add_argument("--title")
    parser.add_argument("--artist", default="")
    parser.add_argument("--seed", type=int, default=0)
    parser.add_argument("--bpm", type=float)
    parser.add_argument("--downbeat-ms", type=float, default=0)
    args = parser.parse_args()
    torch.set_num_threads(min(4, os.cpu_count() or 1))
    *paths, counts = generate_package(
        args.audio, args.output, title=args.title or args.audio.stem, artist=args.artist,
        seed=args.seed, bpm=args.bpm, downbeat_ms=args.downbeat_ms,
    )
    for path in paths:
        print(path)
    print(json.dumps(counts))


if __name__ == "__main__":
    main()