bandlizer 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
bandlizer/__init__.py ADDED
@@ -0,0 +1,4 @@
1
+ """Bandlizer - offline stem separation and synchronized multi-track playback."""
2
+
3
+ __version__ = "0.1.0"
4
+ APP_NAME = "Bandlizer"
bandlizer/__main__.py ADDED
@@ -0,0 +1,4 @@
1
+ from bandlizer.app import main
2
+
3
+ if __name__ == "__main__":
4
+ raise SystemExit(main())
bandlizer/app.py ADDED
@@ -0,0 +1,143 @@
1
+ """CLI & GUI entry point (``bandlizer`` / ``python -m bandlizer``)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ from bandlizer import APP_NAME, __version__
10
+ from bandlizer.config import MODELS
11
+
12
+ _CLI_ONLY_FLAGS = {"-h", "--help", "-V", "--version", "--install-desktop", "--uninstall-desktop"}
13
+
14
+
15
+ def _attach_windows_console_if_needed(argv: list[str]) -> None:
16
+ """When ``bandlizer.exe`` (a Windows GUI script) is run from a terminal with CLI flags
17
+ like ``--help`` or ``--install-desktop``, attach to the parent console so output prints."""
18
+ if sys.platform != "win32":
19
+ return
20
+ if sys.stdout is not None and hasattr(sys.stdout, "fileno"):
21
+ try:
22
+ sys.stdout.fileno()
23
+ return
24
+ except Exception: # noqa: BLE001
25
+ pass
26
+ if not any(a in _CLI_ONLY_FLAGS for a in argv):
27
+ return
28
+ try:
29
+ import ctypes
30
+
31
+ if ctypes.windll.kernel32.AttachConsole(-1): # ATTACH_PARENT_PROCESS
32
+ sys.stdout = open("CONOUT$", "w", encoding="utf-8", buffering=1) # noqa: SIM115
33
+ sys.stderr = open("CONOUT$", "w", encoding="utf-8", buffering=1) # noqa: SIM115
34
+ except Exception: # noqa: BLE001
35
+ pass
36
+
37
+
38
+ def build_parser() -> argparse.ArgumentParser:
39
+ ap = argparse.ArgumentParser(
40
+ prog="bandlizer",
41
+ description=(
42
+ "Bandlizer — Offline stem separator, synchronized multi-track studio, "
43
+ "and Bandle playlist guessing game."
44
+ ),
45
+ formatter_class=argparse.RawDescriptionHelpFormatter,
46
+ epilog=(
47
+ "examples:\n"
48
+ " bandlizer Launch the desktop app\n"
49
+ " bandlizer song.mp3 Open & separate a local audio file\n"
50
+ " bandlizer https://open.spotify.com/track/… Load a Spotify track\n"
51
+ " bandlizer --bandle <playlist-url> Start Bandle game mode on a playlist\n"
52
+ " bandlizer --install-desktop Register in Start Menu (pinnable to Taskbar)\n"
53
+ " bandlizer --uninstall-desktop Remove Start Menu / Desktop shortcuts\n"
54
+ ),
55
+ )
56
+ ap.add_argument(
57
+ "target",
58
+ nargs="?",
59
+ help="optional audio file path, Spotify track URL, or playlist URL to open on launch",
60
+ )
61
+ ap.add_argument(
62
+ "--bandle",
63
+ metavar="PLAYLIST_URL",
64
+ help="launch directly into Bandle game mode with a Spotify, Deezer, Apple Music, or YouTube playlist",
65
+ )
66
+ ap.add_argument(
67
+ "-m",
68
+ "--model",
69
+ choices=list(MODELS),
70
+ help="override separation model on launch",
71
+ )
72
+ ap.add_argument(
73
+ "-d",
74
+ "--device",
75
+ help="override inference device on launch (auto | cpu | cuda | cuda:0 | mps)",
76
+ )
77
+ ap.add_argument(
78
+ "--install-desktop",
79
+ action="store_true",
80
+ help="register Bandlizer as a desktop app (Start Menu shortcut + official icon, pinnable to Taskbar)",
81
+ )
82
+ ap.add_argument(
83
+ "--desktop-shortcut",
84
+ action="store_true",
85
+ help="with --install-desktop, also create a shortcut on the Desktop",
86
+ )
87
+ ap.add_argument(
88
+ "--uninstall-desktop",
89
+ action="store_true",
90
+ help="remove Bandlizer desktop/Start Menu registration",
91
+ )
92
+ ap.add_argument(
93
+ "-V",
94
+ "--version",
95
+ action="version",
96
+ version=f"{APP_NAME} {__version__}",
97
+ )
98
+ return ap
99
+
100
+
101
+ def main(argv: list[str] | None = None) -> int:
102
+ raw_argv = list(sys.argv[1:] if argv is None else argv)
103
+ _attach_windows_console_if_needed(raw_argv)
104
+
105
+ parser = build_parser()
106
+ args = parser.parse_args(raw_argv)
107
+
108
+ if args.install_desktop:
109
+ from bandlizer.desktop import install_desktop
110
+
111
+ created = install_desktop(desktop_shortcut=args.desktop_shortcut)
112
+ print(f"Registered {APP_NAME} as a desktop app:")
113
+ for p in created:
114
+ print(f" - {p}")
115
+ if sys.platform == "win32":
116
+ print("You can now launch Bandlizer from the Start Menu and pin it to your Taskbar.")
117
+ return 0
118
+
119
+ if args.uninstall_desktop:
120
+ from bandlizer.desktop import uninstall_desktop
121
+
122
+ removed = uninstall_desktop()
123
+ if removed:
124
+ print(f"Removed {APP_NAME} desktop registration:")
125
+ for p in removed:
126
+ print(f" - {p}")
127
+ else:
128
+ print(f"No {APP_NAME} desktop shortcuts were found.")
129
+ return 0
130
+
131
+ from bandlizer.ui.main_window import run_app
132
+
133
+ return run_app(
134
+ [sys.argv[0]],
135
+ initial_target=args.target,
136
+ initial_bandle=args.bandle,
137
+ initial_model=args.model,
138
+ initial_device=args.device,
139
+ )
140
+
141
+
142
+ if __name__ == "__main__":
143
+ raise SystemExit(main())
bandlizer/audio_io.py ADDED
@@ -0,0 +1,84 @@
1
+ """Audio decoding/encoding helpers built on soundfile (libsndfile, MP3 capable).
2
+
3
+ All in-memory audio uses float32 arrays shaped ``(frames, channels)``.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from math import gcd
9
+ from pathlib import Path
10
+
11
+ import numpy as np
12
+ import soundfile as sf
13
+ from scipy.signal import resample_poly
14
+
15
+ SUPPORTED_EXPORT_FORMATS = {
16
+ "wav": {"format": "WAV", "subtype": "PCM_16"},
17
+ "flac": {"format": "FLAC", "subtype": "PCM_16"},
18
+ "mp3": {"format": "MP3", "subtype": "MPEG_LAYER_III"},
19
+ }
20
+
21
+ READ_EXTENSIONS = (".mp3", ".wav", ".flac", ".ogg", ".aiff", ".aif")
22
+
23
+
24
+ def load_audio(path: str | Path, target_sr: int | None = None, channels: int | None = 2) -> tuple[np.ndarray, int]:
25
+ """Decode an audio file to float32 ``(frames, channels)``.
26
+
27
+ ``channels=2`` up-mixes mono / down-mixes >2 channels to stereo.
28
+ ``target_sr`` resamples when the file rate differs.
29
+ """
30
+ data, sr = sf.read(str(path), dtype="float32", always_2d=True)
31
+ if channels is not None and data.shape[1] != channels:
32
+ data = _convert_channels(data, channels)
33
+ if target_sr is not None and sr != target_sr:
34
+ data = resample(data, sr, target_sr)
35
+ sr = target_sr
36
+ return np.ascontiguousarray(data, dtype=np.float32), sr
37
+
38
+
39
+ def _convert_channels(data: np.ndarray, channels: int) -> np.ndarray:
40
+ if data.shape[1] == 1:
41
+ return np.repeat(data, channels, axis=1)
42
+ if channels == 1:
43
+ return data.mean(axis=1, keepdims=True)
44
+ if data.shape[1] > channels:
45
+ return data[:, :channels]
46
+ # pad by repeating last channel
47
+ extra = np.repeat(data[:, -1:], channels - data.shape[1], axis=1)
48
+ return np.concatenate([data, extra], axis=1)
49
+
50
+
51
+ def resample(data: np.ndarray, sr_in: int, sr_out: int) -> np.ndarray:
52
+ if sr_in == sr_out:
53
+ return data
54
+ g = gcd(sr_in, sr_out)
55
+ return resample_poly(data, sr_out // g, sr_in // g, axis=0).astype(np.float32)
56
+
57
+
58
+ def save_audio(path: str | Path, data: np.ndarray, sr: int, fmt: str | None = None) -> Path:
59
+ """Write ``(frames, channels)`` float audio. Format is inferred from the extension if not given."""
60
+ path = Path(path)
61
+ fmt = (fmt or path.suffix.lstrip(".")).lower()
62
+ if fmt not in SUPPORTED_EXPORT_FORMATS:
63
+ raise ValueError(f"Unsupported export format: {fmt!r}")
64
+ opts = SUPPORTED_EXPORT_FORMATS[fmt]
65
+ path.parent.mkdir(parents=True, exist_ok=True)
66
+ clipped = np.clip(data, -1.0, 1.0)
67
+ sf.write(str(path), clipped, sr, format=opts["format"], subtype=opts["subtype"])
68
+ return path
69
+
70
+
71
+ def mp3_supported() -> bool:
72
+ return "MP3" in sf.available_formats()
73
+
74
+
75
+ def compute_peaks(data: np.ndarray, buckets: int = 2000) -> np.ndarray:
76
+ """Downsample audio to ``buckets`` peak values in [0, 1] for waveform display."""
77
+ mono = np.abs(data).max(axis=1) if data.ndim == 2 else np.abs(data)
78
+ n = len(mono)
79
+ if n == 0:
80
+ return np.zeros(buckets, dtype=np.float32)
81
+ buckets = min(buckets, n)
82
+ usable = (n // buckets) * buckets
83
+ peaks = mono[:usable].reshape(buckets, -1).max(axis=1)
84
+ return peaks.astype(np.float32)
bandlizer/bandle.py ADDED
@@ -0,0 +1,375 @@
1
+ """Pure-Python Bandle guessing game state machine."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import random
6
+ import re
7
+ from dataclasses import dataclass, field
8
+ from typing import Literal
9
+
10
+ import numpy as np
11
+ from scipy.ndimage import median_filter
12
+ from scipy.signal import butter, sosfiltfilt
13
+
14
+ from bandlizer.playlist import PlaylistData, PlaylistTrack, clean_track_title
15
+
16
+ # Classic Bandle reveal order: rhythm section -> harmonic instruments -> muffled vocals -> vocals last.
17
+ UNLOCK_PRIORITY: dict[str, int] = {
18
+ "drums": 0,
19
+ "bass": 1,
20
+ "piano": 2,
21
+ "guitar": 3,
22
+ "other": 4,
23
+ "muffled vocals": 9,
24
+ "vocals": 10,
25
+ }
26
+
27
+ MUFFLED_VOCALS_NAME = "muffled vocals"
28
+
29
+
30
+ def _yin_frame_pitch(frame: np.ndarray, sr: int, min_hz: float = 80.0, max_hz: float = 950.0,
31
+ threshold: float = 0.22) -> tuple[float, float]:
32
+ """Estimate fundamental frequency (Hz) and voicing confidence [0..1] via FFT-YIN."""
33
+ n = len(frame)
34
+ tau_min = max(2, int(sr / max_hz))
35
+ tau_max = min(n // 2 - 1, int(sr / min_hz))
36
+ if tau_max <= tau_min:
37
+ return 0.0, 0.0
38
+
39
+ # FFT autocorrelation -> YIN difference function d(tau)
40
+ w = n // 2
41
+ x = frame[:w]
42
+ fft_len = 1 << (n - 1).bit_length()
43
+ fx = np.fft.rfft(frame, n=fft_len)
44
+ acf = np.fft.irfft(fx * np.conj(fx), n=fft_len)[: tau_max + 1]
45
+ csum = np.concatenate(([0.0], np.cumsum(frame * frame)))
46
+ # Energy of window [0..w) + shifted window [tau..tau+w) - 2*cross
47
+ e0 = csum[w]
48
+ taus = np.arange(tau_max + 1)
49
+ # Cross-correlation for exact [0..w) against [tau..tau+w)
50
+ fx0 = np.fft.rfft(x, n=fft_len)
51
+ cross = np.fft.irfft(np.conj(fx0) * fx, n=fft_len)[: tau_max + 1]
52
+ e_tau = csum[taus + w] - csum[taus]
53
+ diff = np.maximum(e0 + e_tau - 2.0 * cross, 0.0)
54
+
55
+ # Cumulative mean normalized difference function (CMNDF)
56
+ cmndf = np.ones_like(diff)
57
+ running = np.cumsum(diff[1:])
58
+ idx = np.arange(1, len(diff))
59
+ valid = running > 1e-12
60
+ cmndf[1:][valid] = diff[1:][valid] * idx[valid] / running[valid]
61
+
62
+ # Pick first local minimum below threshold in [tau_min, tau_max]
63
+ seg = cmndf[tau_min : tau_max + 1]
64
+ below = np.where(seg < threshold)[0]
65
+ if below.size:
66
+ i = int(below[0])
67
+ while i + 1 < len(seg) and seg[i + 1] < seg[i]:
68
+ i += 1
69
+ tau = tau_min + i
70
+ dip = float(seg[i])
71
+ else:
72
+ i = int(np.argmin(seg))
73
+ tau = tau_min + i
74
+ dip = float(seg[i])
75
+ if dip > 0.45:
76
+ return 0.0, 0.0
77
+
78
+ # Parabolic interpolation around tau for smooth sub-sample pitch
79
+ if 1 <= tau < tau_max:
80
+ y0, y1, y2 = cmndf[tau - 1], cmndf[tau], cmndf[tau + 1]
81
+ denom = 2.0 * (2.0 * y1 - y0 - y2)
82
+ if abs(denom) > 1e-12:
83
+ tau = tau + (y0 - y2) / denom
84
+
85
+ freq = float(sr / tau) if tau > 0 else 0.0
86
+ conf = float(np.clip(1.0 - dip, 0.0, 1.0))
87
+ return freq, conf
88
+
89
+
90
+ def make_muffled_vocals(vocals: np.ndarray, sample_rate: int) -> np.ndarray:
91
+ """Resynthesize vocals as a pure warm melodic hum/tone (zero voice or lyrics).
92
+
93
+ Tracks the vocal pitch contour and amplitude envelope via YIN, then drives
94
+ a soft sine-based oscillator so only the melody and phrasing are heard in
95
+ exact sample sync with the rest of the band.
96
+ """
97
+ if vocals.size == 0 or sample_rate <= 0:
98
+ return vocals.astype(np.float32, copy=True)
99
+ n_samples = vocals.shape[0]
100
+ n_channels = vocals.shape[1] if vocals.ndim == 2 else 1
101
+ mono = vocals.mean(axis=1).astype(np.float64) if vocals.ndim == 2 else vocals.astype(np.float64)
102
+
103
+ # Pre-bandpass mono into vocal pitch range (75-1200 Hz) to improve pitch tracking
104
+ if n_samples < 64:
105
+ return np.zeros_like(vocals, dtype=np.float32)
106
+ nyq = sample_rate * 0.5
107
+ sos_bp = butter(2, [min(75.0 / nyq, 0.45), min(1200.0 / nyq, 0.95)], btype="band", output="sos")
108
+ tracked = sosfiltfilt(sos_bp, mono)
109
+
110
+ win = min(2048, max(256, 1 << int(np.round(np.log2(sample_rate * 0.046)))))
111
+ hop = max(64, int(sample_rate * 0.010)) # 10 ms frame step
112
+ n_frames = max(1, 1 + max(0, n_samples - win) // hop)
113
+
114
+ freqs = np.zeros(n_frames, dtype=np.float64)
115
+ envs = np.zeros(n_frames, dtype=np.float64)
116
+ noise_floor = max(float(np.sqrt(np.mean(mono * mono))) * 0.12, 2e-3)
117
+
118
+ for fi in range(n_frames):
119
+ s = fi * hop
120
+ frame = tracked[s : s + win]
121
+ if len(frame) < win:
122
+ frame = np.pad(frame, (0, win - len(frame)))
123
+ rms = float(np.sqrt(np.mean(mono[s : s + win] ** 2)))
124
+ if rms < noise_floor:
125
+ continue
126
+ f0, conf = _yin_frame_pitch(frame, sample_rate)
127
+ if f0 > 0.0 and conf > 0.55:
128
+ freqs[fi] = f0
129
+ envs[fi] = rms * min(1.0, (conf - 0.55) / 0.25)
130
+
131
+ # Smooth pitch across voiced frames (removes single-frame octave glitches)
132
+ voiced = freqs > 0
133
+ if np.any(voiced):
134
+ # Fill unvoiced gaps with nearest voiced pitch so phase never jumps during fades
135
+ v_idx = np.where(voiced)[0]
136
+ filled = np.interp(np.arange(n_frames), v_idx, freqs[v_idx])
137
+ if n_frames >= 5:
138
+ filled = median_filter(filled, size=5)
139
+ freqs = filled
140
+ else:
141
+ return np.zeros_like(vocals, dtype=np.float32)
142
+
143
+ # Interpolate frame-rate frequency & envelope smoothly to sample rate
144
+ frame_centers = np.minimum(np.arange(n_frames) * hop + win * 0.5, n_samples - 1)
145
+ sample_idx = np.arange(n_samples, dtype=np.float64)
146
+ f_sig = np.interp(sample_idx, frame_centers, freqs)
147
+ e_sig = np.interp(sample_idx, frame_centers, envs)
148
+
149
+ # Smooth the amplitude envelope (~20 Hz) for soft, click-free note attacks/releases
150
+ sos_env = butter(2, min(20.0 / nyq, 0.45), btype="low", output="sos")
151
+ e_sig = np.maximum(sosfiltfilt(sos_env, e_sig), 0.0)
152
+
153
+ # Warm pure tone: fundamental sine + tiny soft 2nd harmonic (no vocal formants or words)
154
+ phase = 2.0 * np.pi * np.cumsum(f_sig) / sample_rate
155
+ tone = (0.85 * np.sin(phase) + 0.15 * np.sin(2.0 * phase)) * e_sig
156
+
157
+ # Match vocal loudness cleanly so the tone sits nicely in the mix
158
+ orig_rms = float(np.sqrt(np.mean(mono * mono)))
159
+ tone_rms = float(np.sqrt(np.mean(tone * tone)))
160
+ if tone_rms > 1e-6 and orig_rms > 1e-6:
161
+ tone *= min(orig_rms / tone_rms * 0.75, 2.5)
162
+
163
+ tone = np.clip(tone, -0.95, 0.95).astype(np.float32)
164
+ if vocals.ndim == 2:
165
+ return np.repeat(tone[:, None], n_channels, axis=1)
166
+ return tone
167
+
168
+
169
+ def prepare_bandle_stems(
170
+ names: list[str],
171
+ stems: np.ndarray,
172
+ sample_rate: int,
173
+ min_rms: float = 2e-3,
174
+ ) -> tuple[list[str], np.ndarray, list[int]]:
175
+ """Build Bandle stem arrays (inserting muffled vocals before vocals) and stage order."""
176
+ out_names = list(names)
177
+ out_stems = stems
178
+ lower_names = [n.lower() for n in out_names]
179
+ if "vocals" in lower_names and MUFFLED_VOCALS_NAME not in lower_names:
180
+ v_idx = lower_names.index("vocals")
181
+ if float(np.sqrt(np.mean(stems[v_idx] ** 2))) >= min_rms:
182
+ muffled = make_muffled_vocals(stems[v_idx], sample_rate)
183
+ out_names.append(MUFFLED_VOCALS_NAME)
184
+ out_stems = np.concatenate([stems, muffled[None, ...]], axis=0)
185
+ stage_indices = order_playable_stems(out_names, out_stems, min_rms=min_rms)
186
+ return out_names, np.ascontiguousarray(out_stems, dtype=np.float32), stage_indices
187
+
188
+
189
+ def order_playable_stems(
190
+ names: list[str],
191
+ stems: np.ndarray,
192
+ min_rms: float = 2e-3,
193
+ ) -> list[int]:
194
+ """Return stem indices sorted in Bandle reveal order, skipping near-silent stems."""
195
+ ordered = sorted(range(len(names)), key=lambda i: (UNLOCK_PRIORITY.get(names[i].lower(), 5), i))
196
+ audible = [i for i in ordered if float(np.sqrt(np.mean(stems[i] ** 2))) >= min_rms]
197
+ return audible or ordered
198
+
199
+
200
+ def _norm(text: str) -> str:
201
+ return re.sub(r"\s+", " ", (text or "").strip().lower())
202
+
203
+
204
+ def is_matching_guess(guess: str, answer: PlaylistTrack) -> bool:
205
+ """Return True if ``guess`` matches the mystery track (full display or title)."""
206
+ g = _norm(guess)
207
+ if not g:
208
+ return False
209
+ candidates = {
210
+ _norm(answer.display),
211
+ _norm(answer.title),
212
+ _norm(clean_track_title(answer.title)),
213
+ }
214
+ if answer.artist:
215
+ candidates.add(_norm(f"{answer.artist} - {answer.title}"))
216
+ candidates.add(_norm(f"{clean_track_title(answer.title)} - {answer.artist}"))
217
+ candidates.discard("")
218
+ return g in candidates
219
+
220
+
221
+ def rank_suggestions(tracks: list[PlaylistTrack], query: str, limit: int = 50) -> list[PlaylistTrack]:
222
+ """Filter and rank playlist tracks for autocomplete."""
223
+ q = _norm(query)
224
+ if not q:
225
+ return tracks[:limit]
226
+ scored: list[tuple[int, str, PlaylistTrack]] = []
227
+ for t in tracks:
228
+ disp = _norm(t.display)
229
+ title = _norm(t.title)
230
+ artist = _norm(t.artist)
231
+ if disp == q or title == q:
232
+ rank = 0
233
+ elif title.startswith(q) or disp.startswith(q):
234
+ rank = 1
235
+ elif artist.startswith(q):
236
+ rank = 2
237
+ elif q in disp:
238
+ rank = 3
239
+ else:
240
+ continue
241
+ scored.append((rank, disp, t))
242
+ scored.sort(key=lambda item: (item[0], item[1]))
243
+ return [t for _, _, t in scored[:limit]]
244
+
245
+
246
+ @dataclass
247
+ class BandleAttempt:
248
+ kind: Literal["guess", "skip", "giveup"]
249
+ stage_stem: str
250
+ text: str = ""
251
+ correct: bool = False
252
+
253
+
254
+ @dataclass
255
+ class BandleRound:
256
+ answer: PlaylistTrack
257
+ stem_names: list[str]
258
+ stage_indices: list[int]
259
+ unlocked_count: int = 1
260
+ attempts: list[BandleAttempt] = field(default_factory=list)
261
+ finished: bool = False
262
+ won: bool = False
263
+
264
+ def __post_init__(self) -> None:
265
+ if not self.stage_indices:
266
+ self.stage_indices = list(range(len(self.stem_names)))
267
+ self.unlocked_count = max(1, min(self.unlocked_count, len(self.stage_indices)))
268
+
269
+ @property
270
+ def total_stages(self) -> int:
271
+ return len(self.stage_indices)
272
+
273
+ @property
274
+ def current_stage_index(self) -> int:
275
+ return min(self.unlocked_count - 1, self.total_stages - 1)
276
+
277
+ @property
278
+ def current_stage_stem(self) -> str:
279
+ return self.stem_names[self.stage_indices[self.current_stage_index]]
280
+
281
+ @property
282
+ def unlocked_stem_indices(self) -> list[int]:
283
+ """Stem indices currently unlocked (excludes muffled vocals once clear vocals unlock)."""
284
+ raw = list(range(len(self.stem_names))) if self.finished else list(self.stage_indices[: self.unlocked_count])
285
+ unlocked_names = {self.stem_names[i].lower() for i in raw}
286
+ if "vocals" in unlocked_names and MUFFLED_VOCALS_NAME in unlocked_names:
287
+ raw = [i for i in raw if self.stem_names[i].lower() != MUFFLED_VOCALS_NAME]
288
+ return raw
289
+
290
+ @property
291
+ def revealed_stage_indices(self) -> set[int]:
292
+ """All stage stem indices unlocked so far (including muffled vocals chip after vocals unlock)."""
293
+ if self.finished:
294
+ return set(self.stage_indices)
295
+ return set(self.stage_indices[: self.unlocked_count])
296
+
297
+ @property
298
+ def stage_stem_names(self) -> list[str]:
299
+ return [self.stem_names[i] for i in self.stage_indices]
300
+
301
+ def submit_guess(self, guess_text: str) -> BandleAttempt:
302
+ if self.finished:
303
+ raise RuntimeError("Round is already finished")
304
+ stem = self.current_stage_stem
305
+ if is_matching_guess(guess_text, self.answer):
306
+ att = BandleAttempt("guess", stem, guess_text.strip(), correct=True)
307
+ self.attempts.append(att)
308
+ self.won = True
309
+ self.finished = True
310
+ self.unlocked_count = self.total_stages
311
+ return att
312
+
313
+ att = BandleAttempt("guess", stem, guess_text.strip(), correct=False)
314
+ self.attempts.append(att)
315
+ self._advance_after_miss()
316
+ return att
317
+
318
+ def skip(self) -> BandleAttempt:
319
+ if self.finished:
320
+ raise RuntimeError("Round is already finished")
321
+ att = BandleAttempt("skip", self.current_stage_stem, "Skipped", correct=False)
322
+ self.attempts.append(att)
323
+ self._advance_after_miss()
324
+ return att
325
+
326
+ def give_up(self) -> BandleAttempt:
327
+ if self.finished:
328
+ raise RuntimeError("Round is already finished")
329
+ att = BandleAttempt("giveup", self.current_stage_stem, "Gave up", correct=False)
330
+ self.attempts.append(att)
331
+ self.finished = True
332
+ self.won = False
333
+ self.unlocked_count = self.total_stages
334
+ return att
335
+
336
+ def _advance_after_miss(self) -> None:
337
+ if self.unlocked_count < self.total_stages:
338
+ self.unlocked_count += 1
339
+ else:
340
+ self.finished = True
341
+ self.won = False
342
+
343
+
344
+ class BandleSession:
345
+ """Manages anti-repeat song selection and score stats across a playlist."""
346
+
347
+ def __init__(self, playlist: PlaylistData, rng: random.Random | None = None):
348
+ self.playlist = playlist
349
+ self._rng = rng or random.Random()
350
+ self.played_keys: set[str] = set()
351
+ self.rounds_played = 0
352
+ self.rounds_won = 0
353
+ self.streak = 0
354
+ self.best_streak = 0
355
+
356
+ def pick_candidates(self, limit: int = 6) -> list[PlaylistTrack]:
357
+ """Return up to ``limit`` shuffled unplayed tracks (resets pool once exhausted)."""
358
+ unplayed = [t for t in self.playlist.tracks if t.unique_key not in self.played_keys]
359
+ if not unplayed:
360
+ self.played_keys.clear()
361
+ unplayed = list(self.playlist.tracks)
362
+ self._rng.shuffle(unplayed)
363
+ return unplayed[:limit]
364
+
365
+ def mark_played(self, track: PlaylistTrack) -> None:
366
+ self.played_keys.add(track.unique_key)
367
+
368
+ def record_result(self, won: bool) -> None:
369
+ self.rounds_played += 1
370
+ if won:
371
+ self.rounds_won += 1
372
+ self.streak += 1
373
+ self.best_streak = max(self.best_streak, self.streak)
374
+ else:
375
+ self.streak = 0