-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcluster_graph_panel.py
More file actions
860 lines (725 loc) · 32.3 KB
/
cluster_graph_panel.py
File metadata and controls
860 lines (725 loc) · 32.3 KB
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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
import json
import os
import subprocess
import sys
import threading
import webbrowser
from datetime import datetime
import numpy as np
import time
import logging
import tkinter as tk
from tkinter import ttk, messagebox, filedialog
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
from matplotlib.widgets import LassoSelector
from matplotlib.path import Path
from playlist_generator import write_playlist
from clustered_playlists import log_cluster_summary
from io import BytesIO
from PIL import Image, ImageTk
from music_indexer_api import get_tags
from utils.audio_metadata_reader import read_metadata
logger = logging.getLogger(__name__)
class ClusterGraphPanel(ttk.Frame):
"""Interactive scatter plot with lasso selection for playlist creation."""
def __init__(
self,
parent,
tracks,
X: np.ndarray,
X2: np.ndarray,
cluster_func,
cluster_params,
cluster_manager,
algo_key: str,
library_path,
log_callback,
):
super().__init__(parent)
self.tracks = tracks
self.X = X
self.X2 = X2
self.cluster_func = cluster_func
self.cluster_params = cluster_params
self.library_path = library_path
self.log = log_callback
self.cluster_manager = cluster_manager
self.algo_key = algo_key
self._last_size: tuple[int, int] | None = None
self._geometry_ready = False
self._pending_draw_labels: np.ndarray | None = None
self._configure_binding = None
self._map_binding = None
fig = Figure(figsize=(5, 5))
self.ax = fig.add_subplot(111)
self.canvas = FigureCanvasTkAgg(fig, master=self)
self.canvas.get_tk_widget().pack(fill="both", expand=True)
self._bind_first_geometry_event()
self.scatter = None
self._loading_var = tk.StringVar(value="Running clustering …")
self._loading_lbl = ttk.Label(self, textvariable=self._loading_var)
self._loading_lbl.pack(pady=10)
self._clusters_ready = False
self._cluster_thread: threading.Thread | None = None
self._cluster_start_ts: float | None = None
self._start_clustering(cluster_params)
self.lasso = None
self.sel_scatter = None
self.selected_indices: list[int] = []
self.selected_tracks: list[str] = []
self.temp_playlist: list[str] = []
self._remove_lasso_started = False
self._remove_lasso_prev_state = False
self._remove_lasso_confirm_pending = False
self._add_highlight_pending = False
# Hover support widgets will be set later via ``setup_hover``
self.hover_panel = None
self.hover_album_label = None
self.hover_title_label = None
self.hover_artist_label = None
self._prev_hover_index: int | None = None
# Preload album art thumbnails for snappy hover updates
self.album_thumbnails = [self._load_thumbnail(p) for p in tracks]
# External UI widgets (wired up by main_gui)
self.cluster_combo: ttk.Combobox | None = None
self.cluster_select_var: tk.StringVar | None = None
self.manual_cluster_var: tk.StringVar | None = None
self.temp_listbox: tk.Listbox | None = None
self.temp_status_var: tk.StringVar | None = None
self.temp_remove_btn: ttk.Button | None = None
self.canvas.mpl_connect("button_press_event", self._on_canvas_click)
# UI widgets created externally will be assigned after instantiation
lasso_btn: ttk.Widget
def _start_clustering(self, params: dict):
"""Kick off clustering work in a background thread."""
def _worker():
try:
cached = self.cluster_manager.get_cached_labels(self.algo_key, params)
if cached is None:
labels = self.cluster_manager.compute_labels(
self.algo_key, params, self.cluster_func
)
else:
labels = cached
except Exception as exc: # pragma: no cover - defensive path for GUI
self.after(0, lambda: self.log(f"\u2717 Clustering failed: {exc}"))
return
self.after(0, lambda: self._on_clusters_ready(labels, params))
if self._cluster_thread and self._cluster_thread.is_alive():
return
cached = self.cluster_manager.get_cached_labels(self.algo_key, params)
if cached is not None:
self._on_clusters_ready(cached, params)
return
self._clusters_ready = False
self._sync_controls()
self._loading_var.set("Running clustering …")
self._loading_lbl.pack(pady=10)
self._cluster_start_ts = time.perf_counter()
logger.info("[perf] start clustering %s params=%s", self.algo_key, params)
self._cluster_thread = threading.Thread(target=_worker, daemon=True)
self._cluster_thread.start()
# ─── Lasso Handling ─────────────────────────────────────────────────────
def toggle_lasso(self):
"""Enter or exit lasso selection mode."""
self._cancel_temp_lasso_removal()
self._set_lasso_enabled(self.lasso is None)
def _set_lasso_enabled(self, active: bool):
"""Toggle matplotlib lasso state and sync UI controls."""
self._clear_selection()
if not active:
self._add_highlight_pending = False
if active:
if self.lasso is None:
self.lasso = LassoSelector(self.ax, onselect=self._on_lasso_select)
self.log("Lasso mode enabled – draw a shape")
else:
if self.lasso is not None:
self.lasso.disconnect_events()
self.lasso = None
self.log("Lasso mode disabled")
else:
return
if hasattr(self, "lasso_var"):
self.lasso_var.set(active)
self.canvas.draw_idle()
# ─── Hover Metadata Panel ────────────────────────────────────────────────
def setup_hover(self, panel, album_label, title_label, artist_label):
"""Register widgets used for hover display."""
self.hover_panel = panel
self.hover_album_label = album_label
self.hover_title_label = title_label
self.hover_artist_label = artist_label
self.canvas.mpl_connect("motion_notify_event", self._on_motion)
def _load_thumbnail(self, path: str) -> ImageTk.PhotoImage:
"""Return a 64x64 thumbnail for ``path`` or a gray placeholder."""
img = None
try:
_tags, cover_payloads, _error, _reader = read_metadata(path, include_cover=True)
if cover_payloads:
img = Image.open(BytesIO(cover_payloads[0]))
except Exception:
img = None
if img is None:
img = Image.new("RGB", (64, 64), "#777777")
img.thumbnail((64, 64))
return ImageTk.PhotoImage(img)
def _on_motion(self, event):
if not self.hover_panel:
return
if event.inaxes != self.ax:
self._hide_hover()
return
cont, details = self.scatter.contains(event)
if not cont or not details.get("ind"):
self._hide_hover()
return
idx = details["ind"][0]
if self._prev_hover_index == idx:
return
self._prev_hover_index = idx
track = self.tracks[idx]
tags = get_tags(track)
title = tags.get("title") or os.path.basename(track)
artist = tags.get("artist") or "Unknown"
thumb = self.album_thumbnails[idx]
self.hover_album_label.configure(image=thumb)
self.hover_album_label.image = thumb
self.hover_title_label.configure(text=title)
self.hover_artist_label.configure(text=artist)
self.hover_panel.place(relx=1.0, rely=1.0, anchor="se", x=-10, y=-10)
def _hide_hover(self):
if self._prev_hover_index is not None:
self._prev_hover_index = None
if self.hover_panel:
self.hover_panel.place_forget()
def _on_lasso_select(self, verts):
path = Path(verts)
mask = path.contains_points(self.X2)
self.selected_indices = [i for i, v in enumerate(mask) if v]
self.log(f"\u2192 {len(self.selected_indices)} songs selected")
self._update_highlight()
if self._remove_lasso_started:
self._remove_lasso_confirm_pending = bool(self.selected_indices)
if self.temp_remove_btn is not None:
text = "Press to Confirm" if self.selected_indices else "Lasso Selection"
self.temp_remove_btn.configure(text=text)
return
if self._add_highlight_pending and self.selected_indices:
self.selected_tracks = [self.tracks[i] for i in self.selected_indices]
self.add_highlight_to_temp()
self._add_highlight_pending = False
self._set_lasso_enabled(False)
return
def create_temp_playlist(self):
"""Write the temporary playlist to disk and open the folder."""
if not self.temp_playlist:
self.log("\u26a0 No songs in temporary playlist")
return
outfile = self._prompt_playlist_destination("ClusterSelection")
if not outfile:
self.log("\u26a0 Playlist save cancelled")
return
try:
write_playlist(self.temp_playlist, outfile)
except Exception as exc: # pragma: no cover - GUI log
self.log(f"\u2717 Failed to write playlist: {exc}")
return
self.log(f"\u2713 Playlist written: {outfile}")
self._open_folder(os.path.dirname(outfile))
def _prompt_playlist_destination(self, default_prefix: str) -> str | None:
"""Open a save dialog and return the chosen playlist path in Playlists."""
playlists_dir = os.path.join(self.library_path, "Playlists")
os.makedirs(playlists_dir, exist_ok=True)
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
default_name = f"{default_prefix}_{ts}.m3u"
chosen = filedialog.asksaveasfilename(
parent=self,
title="Save Playlist As",
defaultextension=".m3u",
initialdir=playlists_dir,
initialfile=default_name,
filetypes=[("M3U Playlist", "*.m3u"), ("All Files", "*.*")],
)
if not chosen:
return None
return os.path.join(playlists_dir, os.path.basename(chosen))
def _open_folder(self, path: str) -> None:
"""Open ``path`` with the platform default file browser."""
try:
if sys.platform == "win32":
os.startfile(path) # type: ignore[attr-defined]
elif sys.platform == "darwin":
subprocess.run(["open", path], check=False)
else:
subprocess.run(["xdg-open", path], check=False)
except Exception as exc: # pragma: no cover - OS interaction
messagebox.showerror("Open Folder", f"Could not open {path}: {exc}")
# ─── Helpers ────────────────────────────────────────────────────────────
def _clear_selection(self):
self.selected_indices = []
self.selected_tracks = []
if self.sel_scatter is not None:
self.sel_scatter.remove()
self.sel_scatter = None
def _on_canvas_click(self, _event) -> None:
if self._remove_lasso_started and self._remove_lasso_confirm_pending:
self._cancel_temp_lasso_removal()
def _update_highlight(self):
if self.sel_scatter is not None:
self.sel_scatter.remove()
if not self.selected_indices:
self.sel_scatter = None
else:
pts = self.X2[self.selected_indices]
self.sel_scatter = self.ax.scatter(
pts[:, 0],
pts[:, 1],
facecolors="none",
edgecolors="k",
s=60,
)
self.canvas.draw_idle()
# ─── Re-clustering Support ─────────────────────────────────────────────
def _compute_colors(self, labels):
from matplotlib import cm
uniq = sorted([l for l in set(labels) if l >= 0])
base_cmap = cm.get_cmap("tab20")
colors = base_cmap(np.linspace(0, 1, max(len(uniq), 1)))
label_colors = {l: colors[i % len(colors)] for i, l in enumerate(uniq)}
label_colors[-1] = (0.6, 0.6, 0.6, 0.5)
point_colors = [label_colors.get(l, (0.6, 0.6, 0.6, 0.5)) for l in labels]
return point_colors, label_colors
def _draw_clusters(self, labels):
point_colors, self.label_colors = self._compute_colors(labels)
self.labels = labels
if self.scatter is None:
self.scatter = self.ax.scatter(
self.X2[:, 0],
self.X2[:, 1],
c=point_colors,
s=20,
)
self.ax.set_title("Lasso to select text")
else:
self.scatter.set_offsets(self.X2)
self.scatter.set_color(point_colors)
self.canvas.draw_idle()
self._refresh_cluster_options()
def _on_clusters_ready(self, labels, params: dict):
duration_ms = None
if self._cluster_start_ts is not None:
duration_ms = (time.perf_counter() - self._cluster_start_ts) * 1000
self.cluster_params = params
self._clusters_ready = True
if self._loading_lbl.winfo_exists():
self._loading_lbl.pack_forget()
self._render_clusters(labels)
self._force_post_cluster_resize()
log_cluster_summary(labels, self.log)
if duration_ms is not None:
logger.info(
"[perf] clusters ready (%s) in %.1f ms", self.algo_key, duration_ms
)
self._sync_controls()
self._refresh_cluster_options()
def recluster(self, params: dict):
"""Re-run clustering with new ``params`` and redraw the plot."""
if self.lasso is not None:
self.toggle_lasso()
self._clear_selection()
self._loading_var.set("Updating clusters …")
self._loading_lbl.pack(pady=10)
self._start_clustering(params)
def _render_clusters(self, labels) -> None:
"""Finalize layout before drawing clusters to avoid oversized renders."""
def _queue_draw() -> None:
self._pending_draw_labels = labels
self._maybe_draw_after_geometry()
self.after_idle(_queue_draw)
def _bind_first_geometry_event(self) -> None:
widget = self.canvas.get_tk_widget()
def _on_geometry(event):
if self._geometry_ready:
return
w = getattr(event, "width", widget.winfo_width())
h = getattr(event, "height", widget.winfo_height())
if w <= 1 or h <= 1:
return
self._geometry_ready = True
if self._configure_binding:
widget.unbind("<Configure>", self._configure_binding)
if self._map_binding:
widget.unbind("<Map>", self._map_binding)
self._maybe_draw_after_geometry()
self._configure_binding = widget.bind("<Configure>", _on_geometry, add="+")
self._map_binding = widget.bind("<Map>", _on_geometry, add="+")
def _maybe_draw_after_geometry(self) -> None:
if not self._geometry_ready or self._pending_draw_labels is None:
return
labels = self._pending_draw_labels
self._pending_draw_labels = None
try:
self.winfo_toplevel().update_idletasks()
except Exception:
pass
try:
self.canvas.resize_event()
except Exception:
pass
self._draw_clusters(labels)
def final_redraw():
try:
self.winfo_toplevel().update_idletasks()
except Exception:
pass
try:
self.canvas.resize_event()
except Exception:
pass
try:
self.canvas.draw_idle()
except Exception:
pass
self.after_idle(final_redraw)
self.after(30, final_redraw)
def _force_post_cluster_resize(self) -> None:
"""Trigger a resize after clustering to avoid oversized initial renders."""
widget = self.canvas.get_tk_widget()
def _resize_once() -> None:
try:
widget.update_idletasks()
except Exception:
pass
w = widget.winfo_width()
h = widget.winfo_height()
if w <= 1 or h <= 1:
return
self.on_resize(w, h)
self.after_idle(_resize_once)
self.after(30, _resize_once)
def on_resize(self, width: int, height: int) -> None:
"""Resize the matplotlib canvas to the given dimensions."""
if width <= 1 or height <= 1:
return
size = (width, height)
if size == self._last_size:
return
self._last_size = size
widget = self.canvas.get_tk_widget()
widget.configure(width=width, height=height)
fig = self.canvas.figure
dpi = fig.dpi or 72
fig.set_size_inches(max(width / dpi, 1e-2), max(height / dpi, 1e-2), forward=False)
try:
self.canvas.resize_event()
except Exception:
pass
try:
self.canvas.draw_idle()
except Exception:
pass
def _sync_controls(self):
"""Enable/disable controls based on clustering readiness."""
state = "normal" if self._clusters_ready else "disabled"
if hasattr(self, "lasso_btn"):
self.lasso_btn.configure(state=state)
def refresh_control_states(self):
"""Public hook to sync controls after external widgets are attached."""
self._sync_controls()
def _refresh_cluster_options(self):
"""Populate the cluster dropdown with discovered cluster IDs."""
if not hasattr(self, "labels"):
return
clusters = sorted({int(l) for l in set(self.labels) if l >= 0})
if self.cluster_combo is not None:
values = [str(c) for c in clusters]
self.cluster_combo.configure(values=values)
if self.cluster_select_var is not None:
current = self.cluster_select_var.get()
if current not in values and values:
self.cluster_select_var.set(values[0])
if self.temp_status_var is not None:
self.temp_status_var.set(f"Clusters available: {len(clusters)}")
# ─── Cluster-Based Selection Helpers ───────────────────────────────────
def show_current_playlists(self):
"""Display playlists located in the library's Playlists folder."""
if not self.library_path:
messagebox.showinfo("Playlists", "Select a library first.")
return
playlists_dir = os.path.join(self.library_path, "Playlists")
if not os.path.isdir(playlists_dir):
messagebox.showinfo("Playlists", "No Playlists folder found yet.")
return
entries = []
try:
entries = [
f
for f in os.listdir(playlists_dir)
if os.path.isfile(os.path.join(playlists_dir, f))
]
except OSError as exc:
messagebox.showerror("Playlists", f"Could not read folder: {exc}")
return
if not entries:
messagebox.showinfo("Playlists", "No playlists found.")
return
messagebox.showinfo("Playlists", "\n".join(sorted(entries)))
def _set_temp_playlist(self, tracks: list[str]):
self.temp_playlist = list(dict.fromkeys(tracks))
self._sync_temp_listbox()
def _sync_temp_listbox(self):
if self.temp_listbox is None:
return
self.temp_listbox.delete(0, tk.END)
for path in self.temp_playlist:
self.temp_listbox.insert(tk.END, os.path.basename(path))
if self.temp_status_var is not None:
self.temp_status_var.set(f"Temp playlist tracks: {len(self.temp_playlist)}")
def load_cluster(self, cluster_id: int, *, replace_temp: bool = True):
"""Highlight ``cluster_id`` and optionally seed the temp playlist."""
if not hasattr(self, "labels"):
messagebox.showinfo("Clusters", "Clusters not ready yet.")
return
indices = [i for i, lbl in enumerate(self.labels) if lbl == cluster_id]
if not indices:
messagebox.showinfo("Clusters", f"No songs found for cluster {cluster_id}.")
return
self.selected_indices = indices
self.selected_tracks = [self.tracks[i] for i in indices]
self._update_highlight()
self.log(f"→ Loaded cluster {cluster_id}: {len(indices)} songs")
if replace_temp:
self._set_temp_playlist(self.selected_tracks)
def highlight_temp_playlist(self):
"""Highlight all points currently stored in the temp playlist."""
if not self.temp_playlist:
messagebox.showinfo("Selection", "No songs in the temporary playlist.")
return
temp_set = set(self.temp_playlist)
indices = [i for i, track in enumerate(self.tracks) if track in temp_set]
if not indices:
messagebox.showinfo(
"Selection",
"No matching songs from the temporary playlist were found in this view.",
)
return
self.selected_indices = indices
self.selected_tracks = [self.tracks[i] for i in indices]
self._update_highlight()
self.log(f"→ Highlighted {len(indices)} songs from the temporary playlist")
def add_highlight_to_temp(self):
"""Append currently highlighted songs to the temp playlist."""
if not self.selected_indices:
messagebox.showinfo("Selection", "No highlighted songs to add.")
return
current = list(self.temp_playlist)
for idx in self.selected_indices:
track = self.tracks[idx]
if track not in current:
current.append(track)
self._set_temp_playlist(current)
def remove_selected_from_temp(self):
"""Remove highlighted entries from the temp playlist listbox."""
if self.temp_listbox is None:
return
if self._remove_lasso_confirm_pending:
self._confirm_temp_lasso_removal()
return
selected = list(self.temp_listbox.curselection())
if selected:
self._cancel_temp_lasso_removal()
remaining = [t for i, t in enumerate(self.temp_playlist) if i not in selected]
self._set_temp_playlist(remaining)
return
self._begin_temp_lasso_removal()
def begin_add_highlight_flow(self) -> None:
"""Activate lasso (if needed) before adding highlights to the temp list."""
if self._remove_lasso_started:
self._cancel_temp_lasso_removal()
if not self.selected_indices:
self._add_highlight_pending = True
self._set_lasso_enabled(True)
self.log(
"Lasso enabled – draw around songs to add to the temporary playlist"
)
return
self.selected_tracks = [self.tracks[i] for i in self.selected_indices]
self.add_highlight_to_temp()
if self.lasso is not None:
self._set_lasso_enabled(False)
def _begin_temp_lasso_removal(self) -> None:
"""Switch to lasso mode to pick songs for removal."""
self._remove_lasso_started = True
self._remove_lasso_prev_state = self.lasso is not None
self._remove_lasso_confirm_pending = False
if self.temp_remove_btn is not None:
self.temp_remove_btn.configure(text="Lasso Selection")
self._set_lasso_enabled(True)
self.log("Use lasso to select songs to remove from the playlist")
def _confirm_temp_lasso_removal(self) -> None:
"""Remove any lasso-selected points that exist in the temp playlist."""
if not self.selected_indices:
self.log("⚠ No points selected; removal cancelled")
self._cancel_temp_lasso_removal()
return
selected_tracks = [self.tracks[i] for i in self.selected_indices]
temp_set = set(self.temp_playlist)
to_remove = [t for t in selected_tracks if t in temp_set]
if not to_remove:
self.log("⚠ None of the lassoed songs are in the temporary playlist")
self._cancel_temp_lasso_removal()
return
remaining = [t for t in self.temp_playlist if t not in set(to_remove)]
self._set_temp_playlist(remaining)
self.log(f"→ Removed {len(to_remove)} songs from the temporary playlist")
self._cancel_temp_lasso_removal()
def _cancel_temp_lasso_removal(self) -> None:
"""Reset state for lasso-driven removal."""
if self._remove_lasso_started and not self._remove_lasso_prev_state:
self._set_lasso_enabled(False)
self._remove_lasso_started = False
self._remove_lasso_prev_state = False
self._remove_lasso_confirm_pending = False
if self.temp_remove_btn is not None:
self.temp_remove_btn.configure(text="Remove Selected")
self._clear_selection()
def open_3d_graph(self):
"""Generate and open the Three.js 3D cluster graph in the browser."""
if not self.library_path:
messagebox.showinfo("3D Graph", "Select a library first.")
return
docs = os.path.join(self.library_path, "Docs")
info_path = os.path.join(docs, "cluster_info.json")
html_path = os.path.join(docs, "cluster_graph.html")
# If HTML already exists, open it directly
if os.path.isfile(html_path):
webbrowser.open(f"file://{os.path.abspath(html_path)}")
self.log("✓ Opened 3D cluster graph in browser")
return
# Try generating from cluster_info.json
if os.path.isfile(info_path):
try:
from cluster_graph_3d import generate_cluster_graph_html
generate_cluster_graph_html(self.library_path, log_callback=self.log)
webbrowser.open(f"file://{os.path.abspath(html_path)}")
except Exception as exc:
messagebox.showerror("3D Graph", f"Failed to generate graph: {exc}")
return
messagebox.showinfo(
"3D Graph",
"No cluster data found.\n\n"
"Run clustering first — the 3D graph HTML will be generated "
"automatically alongside cluster_info.json.",
)
def open_3d_graph_demo(self):
"""Generate and open a demo 3D graph with 10 random test points."""
if not self.library_path:
messagebox.showinfo("Demo 3D Graph", "Select a library first.")
return
try:
from cluster_graph_3d import generate_cluster_graph_html_from_data
import random
docs = os.path.join(self.library_path, "Docs")
os.makedirs(docs, exist_ok=True)
# Create demo data: 10 random points in 3D space, 2 clusters
random.seed(42)
n_points = 10
demo_data = {
"X_3d": [
[random.uniform(-20, 20) for _ in range(3)]
for _ in range(n_points)
],
"labels": [i % 2 for i in range(n_points)],
"tracks": [f"demo_track_{i}.mp3" for i in range(n_points)],
"metadata": [
{
"title": f"Demo Track {i}",
"artist": "Test Artist",
"duration": 180 + i * 10,
}
for i in range(n_points)
],
"cluster_info": {
"0": {"size": 5},
"1": {"size": 5},
},
"X_downsampled": False,
"X_total_points": n_points,
}
demo_path = os.path.join(docs, "cluster_graph_demo.html")
generate_cluster_graph_html_from_data(demo_data, demo_path, self.log)
webbrowser.open(f"file://{os.path.abspath(demo_path)}")
self.log("✓ Demo 3D graph opened (10 random points, 2 clusters)")
except Exception as exc:
messagebox.showerror(
"Demo 3D Graph", f"Failed to generate demo graph: {exc}"
)
def export_selection_csv(self):
"""Export the currently selected tracks to a CSV file."""
if not self.selected_indices:
messagebox.showinfo("Export", "No songs selected. Use lasso to select first.")
return
tracks_to_export = [self.tracks[i] for i in self.selected_indices]
docs = os.path.join(self.library_path, "Docs") if self.library_path else "."
os.makedirs(docs, exist_ok=True)
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
default_name = f"cluster_selection_{ts}.csv"
chosen = filedialog.asksaveasfilename(
parent=self,
title="Export Selection as CSV",
defaultextension=".csv",
initialdir=docs,
initialfile=default_name,
filetypes=[("CSV Files", "*.csv"), ("All Files", "*.*")],
)
if not chosen:
return
try:
with open(chosen, "w", encoding="utf-8", newline="") as fh:
fh.write("track_path\n")
for track in tracks_to_export:
escaped = track.replace('"', '""')
fh.write(f'"{escaped}"\n')
self.log(f"Exported {len(tracks_to_export)} tracks to {chosen}")
except OSError as exc:
messagebox.showerror("Export", f"Failed to write CSV: {exc}")
def open_param_dialog(self):
"""Show dialog to edit HDBSCAN parameters and redraw clusters."""
dlg = tk.Toplevel(self)
dlg.title("HDBSCAN Parameters")
dlg.grab_set()
cs_var = tk.StringVar(value=str(self.cluster_params.get("min_cluster_size", 5)))
ms_var = tk.StringVar(value=str(self.cluster_params.get("min_samples", "")))
eps_var = tk.StringVar(value=str(self.cluster_params.get("cluster_selection_epsilon", "")))
ttk.Label(dlg, text="Min cluster size:").grid(row=0, column=0, sticky="w")
ttk.Entry(dlg, textvariable=cs_var, width=10).grid(row=0, column=1, sticky="w", padx=(5, 0))
ttk.Label(dlg, text="Min samples:").grid(row=1, column=0, sticky="w")
ttk.Entry(dlg, textvariable=ms_var, width=10).grid(row=1, column=1, sticky="w", padx=(5, 0))
ttk.Label(dlg, text="Epsilon:").grid(row=2, column=0, sticky="w")
ttk.Entry(dlg, textvariable=eps_var, width=10).grid(row=2, column=1, sticky="w", padx=(5, 0))
btns = ttk.Frame(dlg)
btns.grid(row=3, column=0, columnspan=2, pady=(10, 5))
def generate():
try:
params = {"min_cluster_size": int(cs_var.get())}
except ValueError:
messagebox.showerror("Invalid Value", f"{cs_var.get()} is not a valid number")
return
if ms_var.get().strip():
try:
params["min_samples"] = int(ms_var.get())
except ValueError:
messagebox.showerror("Invalid Value", f"{ms_var.get()} is not a valid number")
return
if eps_var.get().strip():
try:
params["cluster_selection_epsilon"] = float(eps_var.get())
except ValueError:
messagebox.showerror("Invalid Value", f"{eps_var.get()} is not a valid number")
return
self.recluster(params)
dlg.destroy()
ttk.Button(btns, text="Generate", command=generate).pack(side="left", padx=5)
ttk.Button(btns, text="Cancel", command=dlg.destroy).pack(side="left", padx=5)