Spaces:
Running
Running
File size: 10,801 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 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 | """Parse osu!taiko ``.osu`` files into beat-grid note events.
Each note becomes an event ``(t, tau, ell, delta)`` as defined in README:
* ``t`` -- position on the beat grid, in beats from the first timing point,
snapped to a 1/48-beat grid (covers 1/16 and 1/12 divisions).
* ``tau`` -- note type (see :class:`NoteType`).
* ``ell`` -- length of rolls and balloons, in beats (0 for hits).
* ``delta`` -- actual time minus grid time, in milliseconds.
Taiko encoding in ``.osu``:
* hit circle: Don, or Ka if the hitsound has whistle (2) or clap (8);
finish (4) makes it a big note.
* slider: drumroll (big with finish); its length follows from pixel length,
slider velocity and beat length.
* spinner: balloon, ending at ``endTime``.
"""
from __future__ import annotations
import bisect
import math
from dataclasses import dataclass, field
from enum import IntEnum
from pathlib import Path
GRID = 48 # sub-beat resolution: lcm of 16 and 12
class NoteType(IntEnum):
DON = 0
KA = 1
BIG_DON = 2
BIG_KA = 3
ROLL = 4
BIG_ROLL = 5
BALLOON = 6
@dataclass
class TimingPoint:
time: float # ms
beat_length: float # ms per beat (uninherited) or negative SV value (inherited)
meter: int
uninherited: bool
kiai: bool
omit_barline: bool = False # effects bit 8: hide the first bar line of this section (red lines)
@property
def sv(self) -> float | None:
"""Slider-velocity multiplier of an inherited (green) point."""
if self.uninherited or self.beat_length >= 0:
return None
return min(max(-100.0 / self.beat_length, 0.1), 10.0)
@dataclass
class Section:
"""A stretch of constant tempo starting at an uninherited timing point."""
time: float
beat_length: float
meter: int
start_beat: float # global beat index of this section's start
@dataclass
class Note:
time: float # ms, as written in the file
type: NoteType
end_time: float # ms; equals time for hits
beat: float # snapped global beat position
grid_index: int # snapped position in 1/GRID beats within the section
divisor: int # smallest beat division that represents the position (1, 2, 3, 4, 6, ...)
beat_in_measure: float
length_beats: float
delta_ms: float
sv: float = 1.0 # effective slider-velocity (scroll) multiplier at this note
@dataclass
class TaikoChart:
metadata: dict[str, str]
difficulty: dict[str, float]
audio_filename: str
mode: int
sections: list[Section]
timing_points: list[TimingPoint]
notes: list[Note] = field(default_factory=list)
kiai: list[tuple[float, float]] = field(default_factory=list) # (start, end) ms
@property
def beatmap_id(self) -> int | None:
v = self.metadata.get("BeatmapID")
return int(v) if v not in (None, "") else None
@property
def beatmapset_id(self) -> int | None:
v = self.metadata.get("BeatmapSetID")
return int(v) if v not in (None, "") else None
@property
def version(self) -> str:
return self.metadata.get("Version", "")
class OsuParseError(ValueError):
pass
def _read_sections(text: str) -> dict[str, list[str]]:
out: dict[str, list[str]] = {}
current = None
for raw in text.splitlines():
line = raw.strip()
if not line or line.startswith("//"):
continue
if line.startswith("[") and line.endswith("]"):
current = line[1:-1]
out.setdefault(current, [])
elif current is not None:
out[current].append(line)
return out
def _kv(lines: list[str]) -> dict[str, str]:
d = {}
for line in lines:
if ":" in line:
k, v = line.split(":", 1)
d[k.strip()] = v.strip()
return d
def _parse_timing_points(lines: list[str]) -> list[TimingPoint]:
tps = []
for line in lines:
p = line.split(",")
if len(p) < 2:
continue
time = float(p[0])
beat_length = float(p[1])
meter = int(p[2]) if len(p) > 2 and p[2] else 4
uninherited = (p[6] != "0") if len(p) > 6 and p[6] else True
effects = int(p[7]) if len(p) > 7 and p[7] else 0
tps.append(TimingPoint(time, beat_length, meter if meter > 0 else 4, uninherited, bool(effects & 1), bool(effects & 8)))
tps.sort(key=lambda t: (t.time, not t.uninherited))
return tps
def _build_sections(tps: list[TimingPoint]) -> list[Section]:
red = [t for t in tps if t.uninherited and t.beat_length > 0]
if not red:
raise OsuParseError("no uninherited timing point")
sections: list[Section] = []
for tp in red:
if sections:
prev = sections[-1]
if tp.time == prev.time: # duplicate red line at same time: later one wins
sections[-1] = Section(tp.time, tp.beat_length, tp.meter, prev.start_beat)
continue
# A red line restarts the bar in osu!, so each section starts on a whole global beat;
# otherwise the 1/48 grid and metrical phase would be misaligned after tempo changes.
raw = prev.start_beat + (tp.time - prev.time) / prev.beat_length
start = float(round(raw)) if abs(raw - round(raw)) < 1e-3 else float(math.ceil(raw))
else:
start = 0.0
sections.append(Section(tp.time, tp.beat_length, tp.meter, start))
return sections
def _section_at(sections: list[Section], times: list[float], t: float) -> Section:
# Notes before the first red line belong to the first section (extrapolated backwards).
i = bisect.bisect_right(times, t) - 1
return sections[max(i, 0)]
def _sv_table(tps: list[TimingPoint]) -> tuple[list[float], list[float]]:
"""(times, sv) step function: red lines reset SV to 1, green lines set it."""
times, vals = [], []
for tp in tps: # sorted by (time, red first), so a green line at the same time wins
v = 1.0 if tp.uninherited else (tp.sv if tp.sv is not None else None)
if v is None:
continue
times.append(tp.time)
vals.append(v)
return times, vals
def _sv_at(table: tuple[list[float], list[float]], t: float) -> float:
times, vals = table
i = bisect.bisect_right(times, t + 1e-6) - 1
return vals[i] if i >= 0 else 1.0
def _snap(sec: Section, t: float) -> tuple[int, float, float]:
"""Return (grid index within section, snapped global beat, delta ms)."""
local = (t - sec.time) / sec.beat_length
n = round(local * GRID)
grid_time = sec.time + n / GRID * sec.beat_length
return n, sec.start_beat + n / GRID, t - grid_time
def _divisor(n: int) -> int:
return GRID // math.gcd(n % GRID, GRID) if n % GRID else 1
def _kiai_ranges(tps: list[TimingPoint]) -> list[tuple[float, float]]:
ranges, start = [], None
for tp in tps:
if tp.kiai and start is None:
start = tp.time
elif not tp.kiai and start is not None:
ranges.append((start, tp.time))
start = None
if start is not None:
ranges.append((start, math.inf))
return ranges
def parse_osu(text: str) -> TaikoChart:
secs = _read_sections(text)
general = _kv(secs.get("General", []))
metadata = _kv(secs.get("Metadata", []))
difficulty = {k: float(v) for k, v in _kv(secs.get("Difficulty", [])).items() if _isfloat(v)}
mode = int(general.get("Mode", "0"))
tps = _parse_timing_points(secs.get("TimingPoints", []))
sections = _build_sections(tps)
sec_times = [s.time for s in sections]
slider_mult = difficulty.get("SliderMultiplier", 1.4)
sv_table = _sv_table(tps)
notes: list[Note] = []
for line in secs.get("HitObjects", []):
p = line.split(",")
if len(p) < 5:
continue
time = float(p[2])
kind = int(p[3])
hs = int(p[4]) if p[4] else 0
big = bool(hs & 4)
sec = _section_at(sections, sec_times, time)
if kind & 1:
ka = bool(hs & (2 | 8))
ntype = (NoteType.BIG_KA if big else NoteType.KA) if ka else (NoteType.BIG_DON if big else NoteType.DON)
end = time
elif kind & 2:
ntype = NoteType.BIG_ROLL if big else NoteType.ROLL
slides = int(p[6]) if len(p) > 6 and p[6] else 1
length = float(p[7]) if len(p) > 7 and p[7] else 0.0
sv = _sv_at(sv_table, time)
end = time + length * slides / (slider_mult * 100.0 * sv) * sec.beat_length
elif kind & 8:
ntype = NoteType.BALLOON
end = float(p[5]) if len(p) > 5 and p[5] else time
else:
continue
n, beat, delta = _snap(sec, time)
local_beat = n / GRID
length_beats = (end - time) / sec.beat_length if end > time else 0.0
notes.append(
Note(
time=time,
type=ntype,
end_time=end,
beat=beat,
grid_index=n,
divisor=_divisor(n),
beat_in_measure=local_beat % sec.meter,
length_beats=length_beats,
delta_ms=delta,
sv=_sv_at(sv_table, time),
)
)
notes.sort(key=lambda x: x.time)
return TaikoChart(
metadata=metadata,
difficulty=difficulty,
audio_filename=general.get("AudioFilename", ""),
mode=mode,
sections=sections,
timing_points=tps,
notes=notes,
kiai=_kiai_ranges(tps),
)
def time_to_beat(sections: list[Section], t: float) -> float:
"""Continuous global beat position of time t (ms)."""
i = max(bisect.bisect_right([s.time for s in sections], t) - 1, 0)
s = sections[i]
return s.start_beat + (t - s.time) / s.beat_length
def beat_to_time(sections: list[Section], b: float) -> float:
i = max(bisect.bisect_right([s.start_beat for s in sections], b) - 1, 0)
s = sections[i]
return s.time + (b - s.start_beat) * s.beat_length
def parse_osu_file(path: str | Path) -> TaikoChart:
return parse_osu(Path(path).read_text(encoding="utf-8-sig", errors="replace"))
def read_mode(path: str | Path) -> int:
"""Read only the Mode field, for fast filtering of large .osu collections."""
with open(path, encoding="utf-8-sig", errors="replace") as f:
for line in f:
s = line.strip()
if s.startswith("Mode:"):
return int(s.split(":", 1)[1].strip() or 0)
if s == "[Metadata]" or s == "[HitObjects]":
break
return 0
def _isfloat(v: str) -> bool:
try:
float(v)
return True
except ValueError:
return False
|