-
-
Notifications
You must be signed in to change notification settings - Fork 140
Expand file tree
/
Copy pathsimilarity.html
More file actions
643 lines (590 loc) · 33 KB
/
Copy pathsimilarity.html
File metadata and controls
643 lines (590 loc) · 33 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
{% extends "includes/layout.html" %}
{% block headAdditions %}
<style>
/* Basic styling for the new checkbox container */
.checkbox-container {
display: flex;
align-items: center;
gap: 0.5rem; /* Space between checkbox and label */
margin-top: 1rem; /* Align with other inputs */
}
.mode-toggle-btn {
background: #3B82F6;
color: white;
border: none;
border-radius: 6px;
padding: 4px 10px;
cursor: pointer;
font-size: 0.8rem;
font-weight: 500;
line-height: 1.2;
text-align: center;
min-width: 55px;
margin-left: 0.5rem;
margin-top: 0;
width: auto;
flex-grow: 0;
vertical-align: middle;
transition: background-color 0.2s;
}
.mode-toggle-btn:hover {
background: #2563EB;
}
.mode-toggle-btn.mood-active {
background: #8B5CF6;
}
.mode-toggle-btn.mood-active:hover {
background: #7C3AED;
}
.mode-toggle-btn.anchor-active {
background: #F59E0B;
}
.mode-toggle-btn.anchor-active:hover {
background: #D97706;
}
</style>
{% endblock %}
{% block content %}
<section>
<header class="page-header">
<h1>AudioMuse-AI - Playlist from Similar Song</h1>
<p>Find tracks similar to a given song, mood or anchor and create a playlist.</p>
</header>
<form id="similarity-form">
<input type="hidden" id="selected_item_id" name="item_id">
<div class="param-group">
<div>
<button type="button" class="mode-toggle-btn" id="similarity-mode-toggle" title="Click to switch Song/Mood">🎵 Song</button>
</div>
<!-- Song mode: autocomplete search -->
<div class="autocomplete-container" id="song-mode-container">
<label for="search_query" class="label-with-tooltip">
Song, Artist or Album name:
<span class="info-tooltip" tabindex="0">
<span class="info-icon"></span>
<span class="tooltip-text">Type the song, artist or album you want to find similar tracks to. As you type, suggestions will appear below.</span>
</span>
</label>
<input type="text" id="search_query" name="search_query" placeholder="Start typing..." autocomplete="off">
<div id="selected_title_display" style="margin-top:0.5rem; font-size:0.9rem; color:var(--text-muted);"></div>
<input type="hidden" id="selected_item_title" name="title">
<div id="selected_artist_display" style="margin-top:0.5rem; font-size:0.9rem; color:var(--text-muted);"></div>
<input type="hidden" id="selected_item_artist" name="artist">
<div id="selected_album_display" style="margin-top:0.5rem; font-size:0.9rem; color:var(--text-muted);"></div>
<input type="hidden" id="selected_item_album" name="album">
<div id="autocomplete-results" class="autocomplete-results hidden"></div>
</div>
<!-- Mood mode: sunburst chart (hidden by default) -->
<div id="mood-mode-container" class="hidden">
<style>
#sunburst-wrapper { max-width: 480px; }
@media (min-width: 768px) { #sunburst-wrapper { max-width: 360px; } }
</style>
<div id="sunburst-wrapper" style="position:relative;width:100%;margin:0 auto;">
<canvas id="sunburst-canvas" class="sunburst-canvas" width="480" height="480" style="width:100%;cursor:pointer;"></canvas>
</div>
<div id="sunburst-selection" class="sunburst-selection" style="text-align:center;margin-top:0.5rem;font-size:0.95rem;font-weight:500;color:var(--text-title);min-height:1.4em;"></div>
<div id="sunburst-breadcrumb" class="sunburst-breadcrumb" style="text-align:center;margin-top:0.25rem;font-size:0.8rem;color:var(--text-muted);cursor:pointer;" title="Click to go back"></div>
<!-- Hidden inputs to keep form submission compatible -->
<select id="mood_select" style="display:none;"><option value="">--</option></select>
<select id="centroid_select" style="display:none;"><option value="">--</option></select>
</div>
<!-- Anchor mode: anchor selection (hidden by default) -->
<div id="anchor-mode-container" class="hidden">
<label for="anchor_select" class="label-with-tooltip">
Anchor:
<span class="info-tooltip" tabindex="0">
<span class="info-icon"></span>
<span class="tooltip-text">Select a pre-built anchor to find songs similar to its sound profile.</span>
</span>
</label>
<select id="anchor_select">
<option value="">-- Select an anchor --</option>
</select>
<div id="no-anchors-msg" class="hidden" style="margin-top:0.5rem; font-size:0.9rem; color:var(--text-muted);">No anchors available. Create anchors from the Alchemy page first.</div>
</div>
<div>
<label for="n" class="label-with-tooltip">
Number of results:
<span class="info-tooltip" tabindex="0">
<span class="info-icon"></span>
<span class="tooltip-text">How many similar songs to find. More results = longer playlist. Typical values: 10-50 songs for a good mix.</span>
</span>
</label>
<input type="number" id="n" name="n" value="10" min="1" max="200">
</div>
</div>
<div class="param-group">
<div class="checkbox-container">
<input type="checkbox" id="eliminate_duplicates" name="eliminate_duplicates" checked>
<label for="eliminate_duplicates" class="label-with-tooltip">
Limit songs per artist in results
<span class="info-tooltip" tabindex="0">
<span class="info-icon"></span>
<span class="tooltip-text">Prevents the playlist from being dominated by one artist. When enabled, limits how many tracks from the same artist can appear in results.</span>
</span>
</label>
</div>
<div class="checkbox-container">
<input type="checkbox" id="radius_similarity" name="radius_similarity" checked>
<label for="radius_similarity" class="label-with-tooltip">
Radius Similarity
<span class="info-tooltip" tabindex="0">
<span class="info-icon"></span>
<span class="tooltip-text">Groups similar songs into "buckets" and orders them for better listening flow. Recommended for smoother transitions between tracks.</span>
</span>
</label>
</div>
<!--<div class="checkbox-container">
<input type="checkbox" id="mood_similarity" name="mood_similarity">
<label for="mood_similarity">Filter by mood similarity (danceability, energy, etc.)</label>
</div>-->
</div>
<button type="submit">
Find Similar Tracks
</button>
</form>
</section>
<section id="results-container" class="hidden">
<h2>Results</h2>
<div id="max-distance" style="font-weight:600; margin-bottom:0.5rem;"></div>
<div id="status"></div>
<!-- Graph visualization removed (not needed) -->
<div id="results-table-wrapper"></div>
</section>
<section id="playlist-creator" class="hidden">
<h3>Create a Playlist from Results</h3>
<form id="playlist-form">
<div class="param-group">
<div>
<label for="playlist_name">Playlist Name:</label>
<input type="text" id="playlist_name" name="playlist_name" required placeholder="e.g., My Awesome Mix">
</div>
</div>
<!-- MODIFIED: Changed button text to be more generic -->
<button type="submit" style="background-color: var(--color-success);">
Create Playlist on Media Server
</button>
</form>
<div id="playlist-status"></div>
</section>
{% endblock %}
{% block bodyAdditions %}
<script src="{{ url_for('static', filename='sunburst.js') }}"></script>
<script>
let _currentMode = 'song';
(() => {
let currentTrackIds = [];
let currentTracks = [];
let searchTimeout;
const PAGE_SIZE = 20;
let autocompleteOffset = 0;
let autocompleteQuery = '';
let isLoadingMore = false;
// Mood centroid data cache
let moodCentroidsCache = null;
const similarityForm = document.getElementById('similarity-form');
const playlistForm = document.getElementById('playlist-form');
const searchInput = document.getElementById('search_query');
const selectedItemIdInput = document.getElementById('selected_item_id');
const autocompleteResults = document.getElementById('autocomplete-results');
const resultsContainer = document.getElementById('results-container');
const playlistCreator = document.getElementById('playlist-creator');
const statusDiv = document.getElementById('status');
const resultsTableWrapper = document.getElementById('results-table-wrapper');
const playlistStatusDiv = document.getElementById('playlist-status');
const moodSelect = document.getElementById('mood_select');
const centroidSelect = document.getElementById('centroid_select');
const modeToggleBtn = document.getElementById('similarity-mode-toggle');
const anchorSelect = document.getElementById('anchor_select');
// --- Mode toggle click handler (Song -> Mood -> Anchor -> Song) ---
const modes = ['song', 'mood', 'anchor'];
const modeLabels = {'song': '\ud83c\udfb5 Song', 'mood': '\ud83c\udfad Mood', 'anchor': '\u2693 Anchor'};
const modeClasses = {'song': '', 'mood': 'mood-active', 'anchor': 'anchor-active'};
const modeContainers = {'song': 'song-mode-container', 'mood': 'mood-mode-container', 'anchor': 'anchor-mode-container'};
modeToggleBtn.addEventListener('click', () => {
const curIdx = modes.indexOf(_currentMode);
const nextIdx = (curIdx + 1) % modes.length;
_currentMode = modes[nextIdx];
modeToggleBtn.textContent = modeLabels[_currentMode];
modeToggleBtn.className = 'mode-toggle-btn' + (modeClasses[_currentMode] ? ' ' + modeClasses[_currentMode] : '');
for (const m of modes) {
document.getElementById(modeContainers[m]).classList.toggle('hidden', m !== _currentMode);
}
});
// --- Sunburst chart for mood centroid selection (external: sunburst.js) ---
let _sunburstState = null;
let selectedMoodLabel = '';
let selectedMoodLabelForPlaylist = '';
function capitalizeLabel(text) {
return text ? text.charAt(0).toUpperCase() + text.slice(1) : text;
}
function findNodePath(current, target) {
if (current === target) return current.name === 'root' ? [] : [current.name];
if (!current.children) return null;
for (const child of current.children) {
const path = findNodePath(child, target);
if (path) return current.name === 'root' ? path : [current.name, ...path];
}
return null;
}
// --- Load mood centroids on page load ---
async function loadMoodCentroids() {
try {
const resp = await fetch(`{{ url_for('voyager_bp.get_mood_centroids_endpoint') }}`);
if (resp.ok) {
moodCentroidsCache = await resp.json();
// Populate hidden mood select for form compat
for (const mood of Object.keys(moodCentroidsCache).sort()) {
const opt = document.createElement('option');
opt.value = mood;
opt.textContent = mood;
moodSelect.appendChild(opt);
}
const tree = SunburstChart.buildTree(moodCentroidsCache);
_sunburstState = SunburstChart.init(
document.getElementById('mood-mode-container'),
tree,
(node, best) => {
moodSelect.value = node.mood;
centroidSelect.innerHTML = '';
const opt = document.createElement('option');
opt.value = best.centroidIndex;
opt.textContent = node.mood.charAt(0).toUpperCase() + node.mood.slice(1) + ' - ' + best.tags.slice(0, 3).join('/');
centroidSelect.appendChild(opt);
centroidSelect.value = best.centroidIndex;
const path = findNodePath(tree, node);
if (path) {
selectedMoodLabel = path.map(capitalizeLabel).join(' — ');
selectedMoodLabelForPlaylist = path.map(capitalizeLabel).join('/');
} else {
selectedMoodLabel = capitalizeLabel(node.mood || '');
selectedMoodLabelForPlaylist = capitalizeLabel(node.mood || '');
}
},
() => { moodSelect.value = ''; centroidSelect.value = ''; selectedMoodLabel = ''; }
);
}
} catch (e) {
console.error('Failed to load mood centroids:', e);
}
}
loadMoodCentroids();
// --- Load anchors on page load ---
async function loadAnchors() {
try {
const resp = await fetch('/api/anchors');
if (resp.ok) {
const data = await resp.json();
const anchors = data.anchors || [];
const noMsg = document.getElementById('no-anchors-msg');
if (anchors.length === 0) {
noMsg.classList.remove('hidden');
} else {
noMsg.classList.add('hidden');
anchors.forEach(a => {
const opt = document.createElement('option');
opt.value = a.id;
opt.textContent = a.name;
anchorSelect.appendChild(opt);
});
}
}
} catch (e) {
console.error('Failed to load anchors:', e);
}
}
loadAnchors();
// (Mood/centroid selection is now handled by the sunburst chart above)
// --- Autocomplete Logic ---
const handleSearchInput = () => {
clearTimeout(searchTimeout);
searchTimeout = setTimeout(async () => {
const searchQuery = searchInput.value.trim();
if (searchQuery.length < 1) {
hideAutocomplete();
return;
}
autocompleteQuery = searchQuery;
autocompleteOffset = 0;
try {
const params = new URLSearchParams({ search_query: searchQuery, start: 0, end: PAGE_SIZE });
const response = await fetch(`{{ url_for('voyager_bp.search_tracks_endpoint') }}?${params}`);
const tracks = await response.json();
autocompleteOffset = tracks.length;
showAutocomplete(tracks, false);
} catch (error) {
console.error('Autocomplete search error:', error);
hideAutocomplete();
}
}, 300); // Debounce requests by 300ms
};
const loadMoreResults = async () => {
if (isLoadingMore) return;
isLoadingMore = true;
try {
const params = new URLSearchParams({ search_query: autocompleteQuery, start: autocompleteOffset, end: autocompleteOffset + PAGE_SIZE });
const response = await fetch(`{{ url_for('voyager_bp.search_tracks_endpoint') }}?${params}`);
const tracks = await response.json();
if (tracks.length > 0) {
autocompleteOffset += tracks.length;
showAutocomplete(tracks, true);
}
} catch (error) {
console.error('Load more error:', error);
} finally {
isLoadingMore = false;
}
};
const showAutocomplete = (tracks, append) => {
if (!append) autocompleteResults.innerHTML = '';
// Remove existing sentinel if any
const existingSentinel = autocompleteResults.querySelector('.autocomplete-load-more');
if (existingSentinel) existingSentinel.remove();
if (tracks.length === 0 && !append) {
autocompleteResults.innerHTML = '<div class="autocomplete-item"><em>No results found</em></div>';
} else {
tracks.forEach(track => {
const itemDiv = document.createElement('div');
itemDiv.className = 'autocomplete-item';
itemDiv.innerHTML = '<div class="title">' + (track.title || 'N/A') + '</div><div class="artist">' + (track.author || 'N/A') + '</div><div class="album">Album: ' + (track.album || 'Unknown') + '</div>';
itemDiv.addEventListener('click', () => selectTrack(track));
autocompleteResults.appendChild(itemDiv);
});
// Add infinite scroll sentinel if we got a full page
if (tracks.length >= PAGE_SIZE) {
const sentinel = document.createElement('div');
sentinel.className = 'autocomplete-load-more autocomplete-item';
sentinel.innerHTML = '<em>Loading more...</em>';
autocompleteResults.appendChild(sentinel);
const observer = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting) {
observer.disconnect();
loadMoreResults();
}
}, { root: autocompleteResults });
observer.observe(sentinel);
}
}
autocompleteResults.classList.remove('hidden');
};
const hideAutocomplete = () => {
autocompleteResults.classList.add('hidden');
};
const selectTrack = (track) => {
selectedItemIdInput.value = track.item_id;
// Store track title (fallback to 'unknown' when missing) and show to user
const titleVal = (track.title || '').trim() || 'unknown';
const titleDisplay = (track.title || '').trim() || 'Unknown';
const titleInputEl = document.getElementById('selected_item_title');
if (titleInputEl) titleInputEl.value = titleVal;
const titleDisplayEl = document.getElementById('selected_title_display');
if (titleDisplayEl) titleDisplayEl.textContent = 'Title: ' + titleDisplay;
// Store artist (fallback to 'unknown' when missing) and show to user
const artistVal = (track.author || '').trim() || 'unknown';
const artistDisplay = (track.author || '').trim() || 'Unknown';
const artistInputEl = document.getElementById('selected_item_artist');
if (artistInputEl) artistInputEl.value = artistVal;
const artistDisplayEl = document.getElementById('selected_artist_display');
if (artistDisplayEl) artistDisplayEl.textContent = 'Artist: ' + artistDisplay;
// Store album (fallback to 'unknown' when missing) and show to user
const albumVal = (track.album || '').trim() || 'unknown';
const albumDisplay = (track.album || '').trim() || 'Unknown';
const albumInputEl = document.getElementById('selected_item_album');
if (albumInputEl) albumInputEl.value = albumVal;
const albumDisplayEl = document.getElementById('selected_album_display');
if (albumDisplayEl) albumDisplayEl.textContent = 'Album: ' + albumDisplay;
hideAutocomplete();
};
searchInput.addEventListener('input', handleSearchInput);
document.addEventListener('click', (e) => {
if (!e.target.closest('.autocomplete-container')) {
hideAutocomplete();
}
});
// Graph visualization removed — kept UI and results table only.
// --- Main Form Submission ---
similarityForm.addEventListener('submit', async function (event) {
event.preventDefault();
const n = document.getElementById('n').value;
const eliminateDuplicates = document.getElementById('eliminate_duplicates').checked;
const radiusSimilarity = document.getElementById('radius_similarity').checked;
resultsContainer.classList.remove('hidden');
playlistCreator.classList.add('hidden');
statusDiv.textContent = 'Searching...';
statusDiv.className = '';
resultsTableWrapper.innerHTML = '';
document.getElementById('max-distance').textContent = '';
let params;
let isVectorMode = (_currentMode === 'mood' || _currentMode === 'anchor');
let playlistLabel;
if (_currentMode === 'mood') {
// --- Mood centroid mode ---
const mood = moodSelect.value;
const centroidIdx = centroidSelect.value;
if (!mood || centroidIdx === '') {
statusDiv.textContent = 'Please select a mood and a centroid.';
statusDiv.className = 'status-error';
return;
}
params = new URLSearchParams({
mood: mood,
centroid_index: centroidIdx,
n: n,
eliminate_duplicates: eliminateDuplicates
});
const selectedOption = centroidSelect.options[centroidSelect.selectedIndex];
playlistLabel = selectedMoodLabel || (selectedOption ? selectedOption.textContent : mood);
} else if (_currentMode === 'anchor') {
// --- Anchor mode ---
const anchorId = anchorSelect.value;
if (!anchorId) {
statusDiv.textContent = 'Please select an anchor.';
statusDiv.className = 'status-error';
return;
}
params = new URLSearchParams({
anchor_id: anchorId,
n: n,
eliminate_duplicates: eliminateDuplicates
});
const selectedOption = anchorSelect.options[anchorSelect.selectedIndex];
playlistLabel = selectedOption ? selectedOption.textContent : 'Anchor';
} else {
// --- Song mode ---
const itemId = selectedItemIdInput.value;
if (!itemId) {
statusDiv.textContent = 'Please select a track from the autocomplete suggestions.';
statusDiv.className = 'status-error';
return;
}
const albumValue = ((document.getElementById('selected_item_album') && document.getElementById('selected_item_album').value) || '').trim() || 'unknown';
params = new URLSearchParams({
item_id: itemId,
n: n,
eliminate_duplicates: eliminateDuplicates,
radius_similarity: radiusSimilarity,
album: albumValue
});
playlistLabel = (document.getElementById('selected_item_title') && document.getElementById('selected_item_title').value) ? document.getElementById('selected_item_title').value : 'Unknown';
}
try {
const response = await fetch(`{{ url_for('voyager_bp.get_similar_tracks_endpoint') }}?${params}`);
const data = await response.json();
if (!response.ok) throw new Error(data.error || `HTTP error! status: ${response.status}`);
if (data.length === 0) {
statusDiv.textContent = 'No similar tracks found.';
return;
}
// Fetch max distance only in song mode
if (!isVectorMode) {
const itemId = selectedItemIdInput.value;
try {
const mdResp = await fetch(`{{ url_for('voyager_bp.get_max_distance_endpoint') }}?item_id=` + encodeURIComponent(itemId));
if (mdResp.ok) {
const md = await mdResp.json();
const maxDistDiv = document.getElementById('max-distance');
if (md && typeof md.max_distance === 'number') {
let text = 'Max distance: ' + md.max_distance.toFixed(4);
const farId = md.farthest_item_id || md.farthest_id || md.item_id || md.max_item_id || md.farthestItemId;
if (farId) {
try {
const tdResp = await fetch(`{{ url_for('voyager_bp.get_track_endpoint') }}?item_id=` + encodeURIComponent(farId));
if (tdResp.ok) {
const td = await tdResp.json();
if (td && (td.title || td.author)) {
text += ' — Farthest track: "' + (td.title || 'Unknown title') + '" by ' + (td.author || 'Unknown artist');
} else {
text += ' — Farthest track ID: ' + farId;
}
} else {
text += ' — Farthest track ID: ' + farId;
}
} catch (errInner) {
console.error('Failed to fetch farthest track metadata:', errInner);
text += ' — Farthest track ID: ' + farId;
}
}
maxDistDiv.textContent = text;
} else {
maxDistDiv.textContent = '';
}
}
} catch (err) {
console.error('Failed to fetch max distance:', err);
}
}
if (!isVectorMode) {
const itemId = selectedItemIdInput.value;
currentTrackIds = [itemId, ...data.map(track => track.item_id)];
currentTracks = [
{
id: itemId,
title: playlistLabel,
author: (document.getElementById('selected_item_artist') && document.getElementById('selected_item_artist').value) || 'Unknown',
album: (document.getElementById('selected_item_album') && document.getElementById('selected_item_album').value) || 'Unknown'
},
...data.map(track => ({id: track.item_id, title: track.title, author: track.author, album: track.album || 'Unknown'}))
];
} else {
currentTrackIds = data.map(track => track.item_id);
currentTracks = data.map(track => ({id: track.item_id, title: track.title, author: track.author, album: track.album || 'Unknown'}));
}
statusDiv.textContent = 'Found ' + data.length + ' similar tracks.';
resultsTableWrapper.innerHTML = renderSongList(data, { metric: songDistanceBadge });
playlistCreator.classList.remove('hidden');
playlistStatusDiv.textContent = '';
let defaultPlaylistName;
if (_currentMode === 'mood') {
defaultPlaylistName = 'Similar to Mood: ' + selectedMoodLabelForPlaylist;
} else if (_currentMode === 'anchor') {
defaultPlaylistName = 'Similar to Anchor: ' + playlistLabel;
} else {
defaultPlaylistName = 'Similar to ' + playlistLabel;
}
document.getElementById('playlist_name').value = defaultPlaylistName;
} catch (error) {
statusDiv.textContent = `Error: ${error.message}`;
statusDiv.className = 'status-error';
console.error('Fetch error:', error);
}
});
// --- Playlist Creation ---
playlistForm.addEventListener('submit', async function (event) {
event.preventDefault();
const playlistName = document.getElementById('playlist_name').value;
playlistStatusDiv.className = '';
if (!playlistName) {
playlistStatusDiv.textContent = 'Please enter a playlist name.';
playlistStatusDiv.className = 'status-error';
return;
}
if (currentTrackIds.length === 0) {
playlistStatusDiv.textContent = 'No tracks to add. Please perform a search first.';
playlistStatusDiv.className = 'status-error';
return;
}
playlistStatusDiv.textContent = 'Creating playlist...';
try {
const response = await fetch("{{ url_for('voyager_bp.create_media_server_playlist') }}", {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
playlist_name: playlistName,
track_ids: currentTrackIds
}),
});
const result = await response.json();
if (!response.ok) throw new Error(result.error || `HTTP error! status: ${response.status}`);
playlistStatusDiv.textContent = result.message;
playlistStatusDiv.className = 'status-success';
} catch (error) {
playlistStatusDiv.textContent = `Error: ${error.message}`;
playlistStatusDiv.className = 'status-error';
console.error('Playlist creation error:', error);
}
});
})();
</script>
<script src="{{ url_for('static', filename='menu.js') }}"></script>
{% endblock %}