-
-
Notifications
You must be signed in to change notification settings - Fork 140
Expand file tree
/
Copy pathlyrics_search.html
More file actions
588 lines (545 loc) · 25 KB
/
Copy pathlyrics_search.html
File metadata and controls
588 lines (545 loc) · 25 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
{% extends "includes/layout.html" %}
{% block headAdditions %}
<style>
.search-container { max-width: 900px; margin: 0 auto; }
.search-container .param-group { margin-bottom: 1.5rem; }
.search-container label { display: block; margin-bottom: 0.5rem; }
.search-box {
width: 100%;
padding: 0.5rem;
font-size: 1rem;
border: 2px solid var(--border-color);
border-radius: 8px;
}
.search-box:focus { outline: none; border-color: var(--color-primary); }
.cache-stats {
background: var(--bg-code);
padding: 1rem;
border-radius: 8px;
margin-bottom: 1.5rem;
font-size: 0.9rem;
}
.cache-stats strong { color: var(--color-primary); }
/* Tabs */
.tabs {
display: flex;
gap: 0.5rem;
margin-bottom: 1.5rem;
border-bottom: 2px solid var(--border-color);
}
.tab-btn {
padding: 0.6rem 1.2rem;
background: transparent;
border: none;
border-bottom: 3px solid transparent;
font-size: 1rem;
font-weight: 500;
cursor: pointer;
color: var(--text-muted);
transition: all 0.2s;
}
.tab-btn.active {
color: var(--color-primary);
border-bottom-color: var(--color-primary);
font-weight: 600;
}
.tab-btn:hover { color: var(--color-primary); }
.tab-pane { display: none; }
.tab-pane.active { display: block; }
/* Axis radio groups */
/* Axis grid (compact, no-scroll) */
.axes-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
gap: 0.75rem;
margin-bottom: 1rem;
}
.axis-block {
background: var(--bg-code);
padding: 0.75rem;
border-radius: 8px;
display: flex;
flex-direction: column;
gap: 0.4rem;
}
.axis-block h3 {
margin: 0;
font-size: 0.92rem;
color: var(--color-primary);
}
.axis-block .axis-desc {
margin: 0;
font-size: 0.78rem;
color: var(--text-muted);
line-height: 1.25;
}
.axis-block select {
width: 100%;
padding: 0.4rem 0.5rem;
font-size: 0.88rem;
border: 1px solid var(--border-color);
border-radius: 6px;
background: var(--bg-body);
color: inherit;
}
.axis-block select:focus { outline: none; border-color: var(--color-primary); }
.axis-block .label-help {
font-size: 0.78rem;
color: var(--text-muted);
line-height: 1.25;
min-height: 1.6em;
}
#search-form button, #axis-form button, #song-form button, #playlist-form button {
width: 100%;
padding: 0.75rem 1.5rem;
font-size: 1rem;
font-weight: 600;
background-color: var(--color-primary);
color: white;
border: none;
border-radius: 8px;
cursor: pointer;
transition: background-color 0.2s;
}
#search-form button:hover, #axis-form button:hover, #song-form button:hover, #playlist-form button:hover {
background-color: var(--color-primary-hover);
}
#search-form button:disabled, #axis-form button:disabled, #song-form button:disabled, #playlist-form button:disabled {
background-color: var(--text-muted);
cursor: not-allowed;
}
.loading-spinner {
text-align: center;
padding: 2rem;
font-size: 1.2rem;
color: var(--text-muted);
}
.error-message {
background: var(--status-failure-bg);
color: var(--status-failure-text);
padding: 1rem;
border-radius: 8px;
margin-top: 1rem;
}
.axes-intro {
display: flex;
align-items: center;
gap: 0.5rem;
margin-bottom: 1rem;
font-size: 0.95rem;
color: var(--text-muted);
}
.axes-intro-text { font-style: italic; }
</style>
{% endblock %}
{% block content %}
<section>
<header class="page-header">
<h1>AudioMuse-AI - Lyrics Semantic Search</h1>
<p>Find songs by meaning. This focuses on the lyrics rather than on the groove of the song.</p>
</header>
{% if not lyrics_enabled %}
<div class="error-message">
<strong>⚠️ Lyrics search is disabled.</strong>
<p>Set <code>LYRICS_ENABLED=true</code> and run analysis with lyrics enabled to populate the index.</p>
</div>
{% else %}
{% if cache_stats.loaded %}
<div class="cache-stats">
<strong>✓ Lyrics Search Ready</strong> |
<strong>{{ cache_stats.song_count }}</strong> songs |
index {{ 'loaded' if cache_stats.index_loaded else 'missing' }} |
axis matrix {{ 'loaded' if cache_stats.axis_loaded else 'missing' }} |
{{ cache_stats.memory_mb }} MB
</div>
{% else %}
<div class="error-message">
<strong>⚠️ No lyrics data found.</strong>
<p>Run analysis with lyrics enabled to populate the lyrics_embedding table and the search index.</p>
</div>
{% endif %}
<div class="search-container">
<div class="tabs">
<button class="tab-btn active" data-tab="axes">By Axis</button>
<button class="tab-btn" data-tab="text">By Text</button>
<button class="tab-btn" data-tab="song">By Song</button>
</div>
<!-- Axis tab -->
<div class="tab-pane active" id="tab-axes">
<form id="axis-form">
<div class="axes-intro">
<span class="info-tooltip" tabindex="0">
<span class="info-icon"></span>
<span class="tooltip-text">Pick one value for one or more axes to compose your search. Each axis describes a different facet of the lyrics (setting, mood, narrative, ...). Leave an axis on “— None —” to ignore it. The more axes you set, the more specific the search.</span>
</span>
<span class="axes-intro-text">Select one value for one or more axes to compose your search.</span>
</div>
<div id="axes-container" class="axes-grid">
{% for axis_name, axis_meta in axes.items() %}
<div class="axis-block" data-axis="{{ axis_name }}">
<h3>{{ axis_name.split('_')[2:] | join(' ') | title }}</h3>
<p class="axis-desc">{{ axis_meta.description }}</p>
<select name="axis-{{ axis_name }}" data-axis="{{ axis_name }}">
<option value="" data-desc="">— None —</option>
{% for label, label_desc in axis_meta.labels.items() %}
<option value="{{ label }}" data-desc="{{ label_desc }}">{{ label }}</option>
{% endfor %}
</select>
<div class="label-help" data-help-for="{{ axis_name }}"></div>
</div>
{% endfor %}
</div>
<div class="param-group">
<label for="axis-limit" class="label-with-tooltip">
Number of results:
<span class="info-tooltip" tabindex="0">
<span class="info-icon"></span>
<span class="tooltip-text">How many songs to return. Higher numbers give more variety but include less-relevant matches. Try 50 for a full playlist or 10–20 for a tight selection.</span>
</span>
</label>
<input type="number" id="axis-limit" name="limit" value="50" min="1" max="500">
</div>
<button type="submit" {% if not cache_stats.axis_loaded %}disabled{% endif %}>
🔍 Search by axes
</button>
</form>
</div>
<!-- Text tab -->
<div class="tab-pane" id="tab-text">
<form id="search-form">
<div class="param-group">
<label for="search-query" class="label-with-tooltip">
Search Query:
<span class="info-tooltip" tabindex="0">
<span class="info-icon"></span>
<span class="tooltip-text">Type a free-form description of the lyrics you’re looking for. The search is semantic: matches are based on <em>meaning</em>, not exact words. “Songs about heartbreak in the city at night” will surface tracks even if those words never appear in their lyrics.</span>
</span>
</label>
<input type="text" id="search-query" name="query" class="search-box"
placeholder="e.g., love"
autocomplete="off" required
{% if not cache_stats.index_loaded %}disabled{% endif %}>
</div>
<div class="param-group">
<label for="text-limit" class="label-with-tooltip">
Number of results:
<span class="info-tooltip" tabindex="0">
<span class="info-icon"></span>
<span class="tooltip-text">How many songs to return. Higher numbers give more variety but include less-relevant matches. Try 50 for a full playlist or 10–20 for a tight selection.</span>
</span>
</label>
<input type="number" id="text-limit" name="limit" value="50" min="1" max="500">
</div>
<button type="submit" {% if not cache_stats.index_loaded %}disabled{% endif %}>
🔍 Search by text
</button>
</form>
</div>
<!-- Song tab -->
<div class="tab-pane" id="tab-song">
{% if sem_grove_stats.loaded %}
<div class="cache-stats" style="margin-bottom:1rem;">
<strong>✓ SemGrove Index Ready</strong> |
<strong>{{ sem_grove_stats.song_count }}</strong> songs |
lyrics {{ sem_grove_stats.w_lyrics * 100 | int }}% /
audio {{ sem_grove_stats.w_audio * 100 | int }}% |
{{ sem_grove_stats.memory_mb }} MB
</div>
{% else %}
<div class="error-message" style="margin-bottom:1rem;">
<strong>⚠️ SemGrove index not built yet.</strong>
<p>Run analysis (lyrics + audio) and then trigger a SemGrove index build to enable this search.</p>
</div>
{% endif %}
<form id="song-form">
<div class="param-group">
<label for="sg-search-query" class="label-with-tooltip">
Seed Song:
<span class="info-tooltip" tabindex="0">
<span class="info-icon"></span>
<span class="tooltip-text">Type to find a song in your library. Select it, then search for songs that share both its lyrical meaning (75%) and its acoustic sound (25%). Lyrics dominate — the audio component prevents jumps across distant genres.</span>
</span>
</label>
<div class="autocomplete-container" id="sg-autocomplete-container">
<input type="text" id="sg-search-query" class="search-box"
placeholder="Start typing a song or artist…"
autocomplete="off"
{% if not sem_grove_stats.loaded %}disabled{% endif %}>
<input type="hidden" id="sg-selected-item-id">
<div id="sg-selected-title-display" style="margin-top:0.5rem; font-size:0.9rem; color:var(--text-muted);"></div>
<div id="sg-selected-artist-display" style="font-size:0.9rem; color:var(--text-muted);"></div>
<div id="sg-selected-album-display" style="font-size:0.9rem; color:var(--text-muted);"></div>
<div id="sg-autocomplete-results" class="autocomplete-results hidden"></div>
</div>
</div>
<div class="param-group">
<label for="song-limit" class="label-with-tooltip">
Number of results:
<span class="info-tooltip" tabindex="0">
<span class="info-icon"></span>
<span class="tooltip-text">How many songs to return. Higher numbers give more variety but include less-relevant matches.</span>
</span>
</label>
<input type="number" id="song-limit" name="limit" value="50" min="1" max="500"
{% if not sem_grove_stats.loaded %}disabled{% endif %}>
</div>
<button type="submit" {% if not sem_grove_stats.loaded %}disabled{% endif %}>
🎵 Find Similar Songs
</button>
</form>
</div>
</div>
{% endif %}
</section>
<section id="results-container" class="hidden">
<h2>Search Results</h2>
<div id="result-count" style="margin-bottom: 1rem; font-weight: 600;"></div>
<div id="results-list"></div>
</section>
<section id="playlist-creator" class="hidden">
<h3>Create a Playlist from Results</h3>
<form id="playlist-form">
<div class="param-group">
<label for="playlist_name">Playlist Name:</label>
<input type="text" id="playlist_name" name="playlist_name"
placeholder="My Lyrics Search Playlist" required>
</div>
<button type="submit">Create Playlist on Media Server</button>
</form>
<div id="playlist-status"></div>
</section>
<script>
document.addEventListener('DOMContentLoaded', function () {
const tabs = document.querySelectorAll('.tab-btn');
const panes = document.querySelectorAll('.tab-pane');
const resultsContainer = document.getElementById('results-container');
const resultsList = document.getElementById('results-list');
const resultCount = document.getElementById('result-count');
const playlistCreator = document.getElementById('playlist-creator');
const playlistForm = document.getElementById('playlist-form');
let currentResults = [];
const lyricsEnabled = "{{ 'true' if lyrics_enabled else 'false' }}" === "true";
if (lyricsEnabled) {
(async function warmupLyricsModel() {
try {
const r = await fetch("{{ url_for('lyrics_search_bp.lyrics_warmup_api') }}", {
method: 'POST',
headers: { 'Content-Type': 'application/json' }
});
const d = await r.json();
if (d.loaded) console.log(`Lyrics model warmed up (expires in ${d.expiry_seconds}s)`);
} catch (e) {
console.error('Failed to warmup lyrics model:', e);
}
})();
}
// ----- Tabs -----
tabs.forEach(btn => {
btn.addEventListener('click', () => {
tabs.forEach(b => b.classList.remove('active'));
panes.forEach(p => p.classList.remove('active'));
btn.classList.add('active');
document.getElementById('tab-' + btn.dataset.tab).classList.add('active');
});
});
// ----- Axis selects: live description under each select -----
document.querySelectorAll('#axes-container select').forEach(sel => {
const axis = sel.dataset.axis;
const helpEl = document.querySelector(`.label-help[data-help-for="${axis}"]`);
const update = () => {
const opt = sel.options[sel.selectedIndex];
helpEl.textContent = opt && opt.dataset.desc ? opt.dataset.desc : '';
};
sel.addEventListener('change', update);
update();
});
// ----- Axis search submit -----
document.getElementById('axis-form').addEventListener('submit', async function (e) {
e.preventDefault();
const targets = {};
document.querySelectorAll('#axes-container select').forEach(sel => {
if (sel.value) targets[sel.dataset.axis] = sel.value;
});
if (Object.keys(targets).length === 0) {
alert('Pick at least one label.');
return;
}
const limit = parseInt(document.getElementById('axis-limit').value, 10) || 50;
await runSearch("{{ url_for('lyrics_search_bp.lyrics_search_axes_api') }}",
{ targets, limit }, '');
});
// ----- SemGrove autocomplete -----
(function () {
const sgInput = document.getElementById('sg-search-query');
const sgResults = document.getElementById('sg-autocomplete-results');
const sgDisplay = document.getElementById('sg-selected-title-display');
const sgItemId = document.getElementById('sg-selected-item-id');
if (!sgInput) return;
const PAGE_SIZE = 20;
let sgOffset = 0, sgQuery = '', sgTimeout, sgLoadingMore = false;
const sgHide = () => sgResults.classList.add('hidden');
const sgSelect = (track) => {
sgItemId.value = track.item_id || '';
sgDisplay.textContent = 'Title: ' + (track.title || 'Unknown');
document.getElementById('sg-selected-artist-display').textContent = 'Artist: ' + (track.author || 'Unknown');
document.getElementById('sg-selected-album-display').textContent = track.album ? 'Album: ' + track.album : '';
sgHide();
};
const sgShow = (tracks, append) => {
if (!append) sgResults.innerHTML = '';
const sentinel = sgResults.querySelector('.autocomplete-load-more');
if (sentinel) sentinel.remove();
if (!tracks.length && !append) {
sgResults.innerHTML = '<div class="autocomplete-item"><em>No results found</em></div>';
} else {
tracks.forEach(t => {
const d = document.createElement('div');
d.className = 'autocomplete-item';
d.innerHTML = `<div class="title">${escapeHtml(t.title||'N/A')}</div><div class="artist">${escapeHtml(t.author||'N/A')}</div><div class="album">Album: ${escapeHtml(t.album||'Unknown')}</div>`;
d.addEventListener('click', () => sgSelect(t));
sgResults.appendChild(d);
});
if (tracks.length >= PAGE_SIZE) {
const more = document.createElement('div');
more.className = 'autocomplete-load-more autocomplete-item';
more.innerHTML = '<em>Loading more…</em>';
sgResults.appendChild(more);
const obs = new IntersectionObserver(entries => {
if (entries[0].isIntersecting) {
obs.disconnect();
if (sgLoadingMore) return;
sgLoadingMore = true;
const p = new URLSearchParams({ search_query: sgQuery, start: sgOffset, end: sgOffset + PAGE_SIZE, index: 'sem_grove' });
fetch(`{{ url_for('voyager_bp.search_tracks_endpoint') }}?${p}`)
.then(r => r.json())
.then(ts => { sgOffset += ts.length; sgShow(ts, true); })
.finally(() => { sgLoadingMore = false; });
}
}, { root: sgResults });
obs.observe(more);
}
}
sgResults.classList.remove('hidden');
};
sgInput.addEventListener('input', () => {
clearTimeout(sgTimeout);
sgTimeout = setTimeout(async () => {
const q = sgInput.value.trim();
if (q.length < 1) { sgHide(); return; }
sgQuery = q; sgOffset = 0;
try {
const p = new URLSearchParams({ search_query: q, start: 0, end: PAGE_SIZE, index: 'sem_grove' });
const r = await fetch(`{{ url_for('voyager_bp.search_tracks_endpoint') }}?${p}`);
const ts = await r.json();
sgOffset = ts.length;
sgShow(ts, false);
} catch (err) { sgHide(); }
}, 300);
});
document.addEventListener('click', e => {
if (!e.target.closest('#sg-autocomplete-container')) sgHide();
});
})();
// ----- Song search submit -----
const sgForm = document.getElementById('song-form');
if (sgForm) {
sgForm.addEventListener('submit', async function (e) {
e.preventDefault();
const item_id = document.getElementById('sg-selected-item-id').value.trim();
if (!item_id) {
alert('Please select a song from the autocomplete list first.');
return;
}
const limit = parseInt(document.getElementById('song-limit').value, 10) || 50;
const seedText = document.getElementById('sg-selected-title-display').textContent || item_id;
await runSearch("{{ url_for('sem_grove_bp.sem_grove_search_api') }}",
{ item_id, limit }, seedText);
});
}
// ----- Text search submit -----
document.getElementById('search-form').addEventListener('submit', async function (e) {
e.preventDefault();
const query = document.getElementById('search-query').value.trim();
if (!query || query.length < 1) {
alert('Please enter at least 1 character.');
return;
}
const limit = parseInt(document.getElementById('text-limit').value, 10) || 50;
await runSearch("{{ url_for('lyrics_search_bp.lyrics_search_text_api') }}",
{ query, limit }, query);
});
async function runSearch(url, body, queryLabel) {
resultsContainer.classList.remove('hidden');
resultsList.innerHTML = '<div class="loading-spinner">🔍 Searching...</div>';
playlistCreator.classList.add('hidden');
try {
const response = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
const data = await response.json();
if (!response.ok) throw new Error(data.error || 'Search failed');
currentResults = data.results || [];
displayResults(currentResults, queryLabel);
} catch (err) {
resultsList.innerHTML = `<div class="error-message">❌ ${err.message}</div>`;
}
}
function displayResults(results, queryLabel) {
if (!results.length) {
resultsList.innerHTML = '<p>No results. Try different inputs.</p>';
resultCount.textContent = '';
return;
}
const visibleCount = results.filter(r => !r.is_seed).length;
resultCount.textContent = queryLabel
? `Found ${visibleCount} matches for "${queryLabel}"`
: `Found ${visibleCount} matches`;
resultsList.innerHTML = renderSongList(results, { skipSeed: true, metric: songSimilarityBadge });
playlistCreator.classList.remove('hidden');
}
// ----- Playlist creation (re-uses voyager_bp endpoint, like the CLAP page) -----
playlistForm.addEventListener('submit', async function (e) {
e.preventDefault();
const statusDiv = document.getElementById('playlist-status');
statusDiv.className = '';
if (!currentResults.length) {
statusDiv.textContent = 'No results to create playlist from';
statusDiv.className = 'status-error';
return;
}
const name = document.getElementById('playlist_name').value.trim();
if (!name) {
statusDiv.textContent = 'Please enter a playlist name';
statusDiv.className = 'status-error';
return;
}
statusDiv.textContent = 'Creating playlist...';
try {
const resp = await fetch("{{ url_for('voyager_bp.create_media_server_playlist') }}", {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
playlist_name: name,
track_ids: currentResults.map(r => r.item_id),
}),
});
const data = await resp.json();
if (!resp.ok) throw new Error(data.error || `HTTP ${resp.status}`);
statusDiv.textContent = data.message;
statusDiv.className = 'status-success';
} catch (err) {
statusDiv.textContent = `Error: ${err.message}`;
statusDiv.className = 'status-error';
}
});
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
});
</script>
<script src="{{ url_for('static', filename='menu.js') }}"></script>
{% endblock %}