From cd6f2a8fa31e52289f3808de5e661f796fe0ad75 Mon Sep 17 00:00:00 2001 From: wlkns-dev Date: Mon, 2 Nov 2026 10:42:10 +0100 Subject: [PATCH] feat(export): implement UltraStar writer and reader for song.txt --- src/songsplit/export/__init__.py | 4 +- src/songsplit/export/ultrastar.py | 247 +++++++++++++++++++++++++++++- tests/test_ultrastar.py | 81 ++++++++++ 3 files changed, 327 insertions(+), 5 deletions(-) create mode 100644 tests/test_ultrastar.py diff --git a/src/songsplit/export/__init__.py b/src/songsplit/export/__init__.py index 22d300e..30ee80b 100644 --- a/src/songsplit/export/__init__.py +++ b/src/songsplit/export/__init__.py @@ -1,5 +1,5 @@ """Export modules.""" -from songsplit.export.ultrastar import export_ultrastar +from songsplit.export.ultrastar import UltraStarNote, UltraStarSong, export_ultrastar, parse_ultrastar -__all__ = ["export_ultrastar"] +__all__ = ["export_ultrastar", "parse_ultrastar", "UltraStarSong", "UltraStarNote"] diff --git a/src/songsplit/export/ultrastar.py b/src/songsplit/export/ultrastar.py index aa96962..0ca668f 100644 --- a/src/songsplit/export/ultrastar.py +++ b/src/songsplit/export/ultrastar.py @@ -1,8 +1,249 @@ -"""UltraStar format export and import.""" +"""UltraStar format export (Writer) and import/parsing (Reader). +Format specifications: +- Headers: #TITLE, #ARTIST, #MP3, #BPM, #GAP, #LANGUAGE +- Note types: + ': ' regular note + '* ' golden note + 'F ' freestyle note + '- ' line break + 'E' end of song +- Beat resolution in UltraStar: 4 ticks per beat (16th notes). +- Pitch in UltraStar: Halftones relative to C4 (MIDI 60). +""" + +import json +import re from pathlib import Path +from songsplit.schema.meta import MetaDocument +from songsplit.schema.tempo import TempoDocument +from songsplit.schema.vocals import VocalsDocument +from songsplit.tempo import sec_to_beat + def export_ultrastar(song_dir: Path) -> Path: - """Export song package to UltraStar song.txt.""" - raise NotImplementedError("UltraStar export will be implemented in M2.") + """Export song package directory to UltraStar song.txt. + + Reads meta.json, vocals.json, and tempo.json if present. + """ + song_dir = song_dir.resolve() + meta_file = song_dir / "meta.json" + vocals_file = song_dir / "vocals.json" + tempo_file = song_dir / "tempo.json" + output_txt = song_dir / "song.txt" + + if not vocals_file.exists(): + raise FileNotFoundError(f"vocals.json not found in {song_dir}") + + with open(vocals_file, encoding="utf-8") as f: + vocals = VocalsDocument.model_validate(json.load(f)) + + meta = None + if meta_file.exists(): + with open(meta_file, encoding="utf-8") as f: + meta = MetaDocument.model_validate(json.load(f)) + + tempo = None + if tempo_file.exists(): + with open(tempo_file, encoding="utf-8") as f: + tempo = TempoDocument.model_validate(json.load(f)) + + title = meta.title if meta and meta.title else song_dir.name + artist = meta.artist if meta and meta.artist else "Unknown Artist" + language = meta.language if meta and meta.language else "German" + + # Find earliest vocal syllable for GAP + first_syllable_sec = 0.0 + for line in vocals.lines: + if line.syllables: + first_syllable_sec = line.syllables[0].start + break + + # Determine reference BPM + if tempo and tempo.anchors: + base_bpm = tempo.anchors[0].bpm + else: + base_bpm = 120.0 + + # In UltraStar, #BPM is 4x standard BPM (4 beats per quarter note) + ultrastar_bpm = base_bpm * 4.0 + gap_ms = int(max(0.0, first_syllable_sec) * 1000.0) + + # Audio reference file: vocals.wav if present, else original file + mp3_name = "stems/vocals.wav" if (song_dir / "stems" / "vocals.wav").exists() else "extracted.wav" + + out_lines = [ + f"#TITLE:{title}", + f"#ARTIST:{artist}", + f"#MP3:{mp3_name}", + f"#BPM:{ultrastar_bpm:.2f}", + f"#GAP:{gap_ms}", + f"#LANGUAGE:{language}", + ] + + def sec_to_ultrastar_beat(sec: float) -> int: + rel_sec = max(0.0, sec - (gap_ms / 1000.0)) + if tempo and tempo.anchors: + quarter_beats = sec_to_beat(rel_sec, tempo) + return max(0, int(round(quarter_beats * 4.0))) + else: + beats_per_sec = base_bpm / 60.0 + return max(0, int(round(rel_sec * beats_per_sec * 4.0))) + + current_beat = 0 + for line_idx, line in enumerate(vocals.lines): + if not line.syllables: + continue + + for syl in line.syllables: + syl_start_beat = sec_to_ultrastar_beat(syl.start) + syl_end_beat = sec_to_ultrastar_beat(syl.end) + duration_beats = max(1, syl_end_beat - syl_start_beat) + + # Prevent overlap with previous syllable in same line + if syl_start_beat < current_beat: + syl_start_beat = current_beat + + current_beat = syl_start_beat + duration_beats + + # UltraStar pitch relative to C4 (MIDI 60) + pitch = int(round(syl.midi - 60.0)) + tag = "*" if syl.golden else ":" + + # Preserve trailing space or text + txt = syl.text + out_lines.append(f"{tag} {syl_start_beat} {duration_beats} {pitch} {txt}") + + # Add line break if not the last line + if line_idx < len(vocals.lines) - 1: + line_break_beat = current_beat + 2 + out_lines.append(f"- {line_break_beat}") + current_beat = line_break_beat + 1 + + out_lines.append("E") + out_lines.append("") + + with open(output_txt, "w", encoding="utf-8") as f: + f.write("\n".join(out_lines)) + + return output_txt + + +class UltraStarNote: + """A parsed note from an UltraStar file.""" + + def __init__( + self, + note_type: str, + start_beat: int, + duration: int, + pitch: int, + text: str, + start_sec: float = 0.0, + end_sec: float = 0.0, + midi: float = 60.0, + ): + self.note_type = note_type + self.start_beat = start_beat + self.duration = duration + self.pitch = pitch + self.text = text + self.start_sec = start_sec + self.end_sec = end_sec + self.midi = midi + + +class UltraStarSong: + """A complete parsed UltraStar song structure.""" + + def __init__(self, headers: dict[str, str], lines: list[list[UltraStarNote]]): + self.headers = headers + self.lines = lines + + @property + def title(self) -> str: + return self.headers.get("TITLE", "") + + @property + def artist(self) -> str: + return self.headers.get("ARTIST", "") + + @property + def bpm(self) -> float: + # Standard quarter-note BPM + return float(self.headers.get("BPM", "480").replace(",", ".")) / 4.0 + + @property + def gap_ms(self) -> float: + return float(self.headers.get("GAP", "0").replace(",", ".")) + + +def parse_ultrastar(file_path: Path) -> UltraStarSong: + """Parse an UltraStar .txt file into structured notes and absolute times in seconds.""" + headers: dict[str, str] = {} + lines: list[list[UltraStarNote]] = [] + current_line: list[UltraStarNote] = [] + + with open(file_path, encoding="utf-8", errors="replace") as f: + content = f.read() + + raw_lines = content.splitlines() + + for raw in raw_lines: + line = raw.rstrip("\r\n") + if not line or not line.strip(): + continue + + if line.startswith("#"): + # Header line: #KEY:VALUE + match = re.match(r"^#([A-Za-z0-9_-]+):(.*)$", line.strip()) + if match: + k, v = match.group(1).upper(), match.group(2).strip() + headers[k] = v + continue + + if line.startswith("E"): + # End of song + if current_line: + lines.append(current_line) + current_line = [] + break + + if line.startswith("-"): + # Line break + if current_line: + lines.append(current_line) + current_line = [] + continue + + # Note line: : 10 4 2 text + match = re.match(r"^([:*F])\s+(-?\d+)\s+(\d+)\s+(-?\d+)\s*(.*)$", line) + if match: + ntype, s_beat, dur, pitch, text = match.groups() + note = UltraStarNote( + note_type=ntype, + start_beat=int(s_beat), + duration=int(dur), + pitch=int(pitch), + text=text, + ) + current_line.append(note) + + if current_line: + lines.append(current_line) + + # Calculate absolute timings in seconds for each note + raw_bpm = float(headers.get("BPM", "480").replace(",", ".")) + gap_sec = float(headers.get("GAP", "0").replace(",", ".")) / 1000.0 + + # UltraStar tick duration in seconds = 60.0 / BPM + sec_per_tick = 60.0 / raw_bpm if raw_bpm > 0 else 0.125 + + for line_notes in lines: + for note in line_notes: + note.start_sec = gap_sec + (note.start_beat * sec_per_tick) + note.end_sec = note.start_sec + (note.duration * sec_per_tick) + note.midi = float(note.pitch + 60) + + return UltraStarSong(headers=headers, lines=lines) diff --git a/tests/test_ultrastar.py b/tests/test_ultrastar.py new file mode 100644 index 0000000..b596dd8 --- /dev/null +++ b/tests/test_ultrastar.py @@ -0,0 +1,81 @@ +"""Unit tests for UltraStar writer and reader round-trip.""" + +from pathlib import Path + +from songsplit.export.ultrastar import export_ultrastar, parse_ultrastar +from songsplit.schema.meta import MetaDocument, SourceFileInfo +from songsplit.schema.tempo import TempoAnchor, TempoDocument +from songsplit.schema.vocals import VocalLine, VocalsDocument, VocalSyllable + + +def test_ultrastar_writer_and_reader(tmp_path: Path): + song_dir = tmp_path / "song_pkg" + song_dir.mkdir(parents=True, exist_ok=True) + + # 1. Prepare meta.json + meta = MetaDocument( + title="Test Song", + artist="Test Artist", + language="de", + duration_sec=30.0, + source_file=SourceFileInfo(path="/tmp/test.mp3", sha256="abc", size_bytes=100), + created_at="2026-11-02T10:00:00Z", + ) + (song_dir / "meta.json").write_text(meta.model_dump_json(indent=2)) + + # 2. Prepare tempo.json (120 BPM) + tempo = TempoDocument(anchors=[TempoAnchor(sec=0.5, beat=0.0, bpm=120.0)]) + (song_dir / "tempo.json").write_text(tempo.model_dump_json(indent=2)) + + # 3. Prepare vocals.json + vocals = VocalsDocument( + lines=[ + VocalLine( + start=0.5, + end=2.0, + syllables=[ + VocalSyllable(text="Hal-", start=0.5, end=1.0, midi=60.0), + VocalSyllable(text="lo ", start=1.0, end=2.0, midi=62.0), + ], + ), + VocalLine( + start=3.0, + end=4.5, + syllables=[ + VocalSyllable(text="Welt", start=3.0, end=4.5, midi=64.0), + ], + ), + ] + ) + (song_dir / "vocals.json").write_text(vocals.model_dump_json(indent=2)) + + # 4. Export to UltraStar song.txt + txt_path = export_ultrastar(song_dir) + assert txt_path.exists() + + content = txt_path.read_text(encoding="utf-8") + assert "#TITLE:Test Song" in content + assert "#ARTIST:Test Artist" in content + assert "#BPM:480.00" in content # 120 * 4 = 480 + assert "#GAP:500" in content # 0.5s = 500 ms + assert "E" in content + + # 5. Parse back using parse_ultrastar + parsed = parse_ultrastar(txt_path) + assert parsed.title == "Test Song" + assert parsed.artist == "Test Artist" + assert parsed.bpm == 120.0 + assert parsed.gap_ms == 500.0 + + assert len(parsed.lines) == 2 + line1 = parsed.lines[0] + assert len(line1) == 2 + assert line1[0].text == "Hal-" + assert line1[0].midi == 60.0 + assert line1[1].text == "lo " + assert line1[1].midi == 62.0 + + line2 = parsed.lines[1] + assert len(line2) == 1 + assert line2[0].text == "Welt" + assert line2[0].midi == 64.0