mirror of
https://github.com/kilyabin/psysonic.git
synced 2026-07-22 14:35:41 +00:00
feat(enrichment): oximedia BPM/mood facts, mood search, and queue display (#863)
* feat(enrichment): oximedia BPM/mood facts, mood search, and queue UI Run client-side oximedia analysis after CPU seed and persist BPM, mood JSON, and searchable mood_tag facts. Add product mood groups (joy/sadness/dance/work/ romance) with Advanced Search filter on the local index, queue BPM/mood display, migration 008 mood_tag index, and refreshed licenses for oximedia crates. * fix(enrichment): keep mood_groups module comment in English * feat(search): virtual mood groups, anger filter, and Advanced Search UX Expand mood search via overlapping virtual groups (tag expansion only), add anger/Злость group, skip album/artist shortcuts for track-only filters, and simplify mood search UI (songs-only, hide type tabs). Fix CustomSelect spurious scrollbar on short option lists. * feat(analysis): unified track analysis plan and enqueue path Add TrackAnalysisPlan (waveform, LUFS, enrichment) with a single enqueue_track_analysis entry for all byte-backed triggers. Run enrichment when cache is full but library facts are missing; route playback, cache, and backfill through the planner. Fix browseTextSearch LocalSearchOpts tsc gap and remove obsolete read_seed_bytes_if_needed helper. * fix(analysis): wire playback dispatch, preload enrichment, and UI refresh Route stream, gapless, preload, and local-file playback through analysis_dispatch so BPM/mood enrichment runs when waveform/LUFS are already cached. Fix audio_preload cache-hit and hot-cache paths, emit preload-cancelled for retry, and add analysis:enrichment-updated plus content_cache_coverage key resolution. * fix(audio): preload local files from disk and stop analysis retry loop Seed hot/offline next tracks via LocalFilePlayback (512 MiB) instead of copying into the RAM preload slot. Keep bytePreloadingId set after preload-ready so progress ticks do not re-invoke audio_preload every second. * fix(enrichment): clippy, album bpm filter routing, and queue mood display Clippy-clean analysis_dispatch and engine imports; restrict track-derived album routing to mood_group/mood_tag only so bpm is skipped on album queries. Log enrichment plan errors with retry-all plan; filter queue mood labels to oximedia ids. * fix(enrichment): simplify mood_tag backfill branch in plan_track_enrichment Remove empty if-block; keep same behaviour when backfill fails and moods row exists. * docs: CHANGELOG and credits for track enrichment PR #863 * docs(credits): track enrichment PR #863 contributor line * chore(enrichment): clippy-clean plan branch and trim dead exports Collapse mood_tag backfill if for clippy; remove unused moodGroupById and OXIMEDIA_MOOD_LABELS re-exports; stop poll when server BPM is already known. * fix(enrichment): close R2/S1–S3 limits and Song Info BPM fallback Return TrackEnrichmentOutcome::Failed on oximedia errors so retries are not masked as complete; extract mood Advanced Search SQL, unify top-3 mood tag selection in mood_groups with TS invariant tests, and show measured BPM in Song Info when tag BPM is missing or zero. * fix(enrichment): restore offline coverage and show mood in Song Info Add unit tests for offline download cancel/clear registry after the analysis seed refactor dropped read_seed_bytes coverage; show localized mood labels in Song Info when library enrichment facts exist. * fix(enrichment): soft mood scoring and unblock offline cancel tests Replace oximedia quadrant happy/excited mapping with valence/arousal soft scores across all mood tags for display, storage, and backfill; fix offline cancel unit tests that deadlocked by calling clear while holding the global offline_cancel_flags mutex. * fix(enrichment): dedupe joy cluster and cap mood display at two labels Never show happy and excited together; pick one tag per V/A cluster, tighten oximedia recalibration, and limit queue/Song Info to two moods that pass a relative score floor. * fix(enrichment): disable oximedia mood labels in UI and search tags Oximedia 0.1.7 mood is a spectral energy heuristic, not independent mood weights; valence correlates with loud/bright audio and false-labels metal and lyrical tracks as happy. Hide queue/Song Info mood and stop writing mood_tag facts until a reliable detector lands; keep V/A/moods JSON stored. * fix(enrichment): disable oximedia mood analysis and add BPM advanced search Stop planning, running, and storing oximedia mood facts; purge accumulated mood rows via migration 009. Hide mood filters in Advanced Search, expose BPM range filter with dual-storage resolution, and show a BPM column in song results when that filter is active. * feat(search): analysis BPM priority, source tooltip, and filter UX Prefer analysis track_fact over file tags for BPM resolution; show source in list tooltips. Validate BPM range on blur, add clear button, fix double tooltip. * fix(enrichment): prefer analysis BPM in Song Info and queue tech row Show measured track_fact BPM before file tags until analysis completes; pick the highest-confidence analysis fact when several exist.
This commit is contained in:
@@ -2,13 +2,16 @@ import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import { onInvoke } from '@/test/mocks/tauri';
|
||||
import { useAuthStore } from '@/store/authStore';
|
||||
import { useLibraryIndexStore } from '@/store/libraryIndexStore';
|
||||
import { runLocalAdvancedSearch, runLocalSongBrowse } from './advancedSearchLocal';
|
||||
import { runLocalAdvancedSearch, runLocalSongBrowse, trackToSong } from './advancedSearchLocal';
|
||||
|
||||
const opts = (over: Partial<Parameters<typeof runLocalAdvancedSearch>[1]> = {}) => ({
|
||||
query: '',
|
||||
genre: '',
|
||||
yearFrom: '',
|
||||
yearTo: '',
|
||||
bpmFrom: '',
|
||||
bpmTo: '',
|
||||
moodGroup: '',
|
||||
resultType: 'all' as const,
|
||||
...over,
|
||||
});
|
||||
@@ -58,6 +61,41 @@ describe('runLocalAdvancedSearch', () => {
|
||||
expect(captured).toMatchObject({ request: { libraryScope: 'lib7' } });
|
||||
});
|
||||
|
||||
it('passes bpm between filter to library_advanced_search', async () => {
|
||||
ready();
|
||||
let captured: unknown;
|
||||
onInvoke('library_advanced_search', (args) => {
|
||||
captured = args;
|
||||
return {
|
||||
artists: [],
|
||||
albums: [],
|
||||
tracks: [],
|
||||
totals: { artists: 0, albums: 0, tracks: 0 },
|
||||
source: 'local',
|
||||
};
|
||||
});
|
||||
await runLocalAdvancedSearch('s1', opts({ bpmFrom: '120', bpmTo: '130' }), 100);
|
||||
expect(captured).toMatchObject({
|
||||
request: { filters: [{ field: 'bpm', op: 'between', value: 120, valueTo: 130 }] },
|
||||
});
|
||||
});
|
||||
|
||||
it('trackToSong keeps resolved bpm and source over rawJson tag', () => {
|
||||
const song = trackToSong({
|
||||
serverId: 's1',
|
||||
id: 't1',
|
||||
title: 'T',
|
||||
album: 'Alb',
|
||||
durationSec: 100,
|
||||
syncedAt: 0,
|
||||
bpm: 128,
|
||||
bpmSource: 'analysis',
|
||||
rawJson: { id: 't1', title: 'T', artist: 'A', album: 'Alb', albumId: 'al1', duration: 100, bpm: 90 },
|
||||
});
|
||||
expect(song.bpm).toBe(128);
|
||||
expect(song.localBpmSource).toBe('analysis');
|
||||
});
|
||||
|
||||
it('prefers rawJson, falls back to hot columns, and reports the full total', async () => {
|
||||
ready();
|
||||
onInvoke('library_advanced_search', () => ({
|
||||
|
||||
@@ -25,15 +25,19 @@ import { search } from '../../api/subsonicSearch';
|
||||
import { libraryScopeForServer } from '../../api/subsonicClient';
|
||||
import { libraryIsReady } from './libraryReady';
|
||||
import { logLibrarySearch, timed } from './libraryDevLog';
|
||||
import { OXIMEDIA_MOOD_SEARCH_ENABLED } from './trackEnrichment';
|
||||
|
||||
export type AdvancedResultType = 'all' | 'artists' | 'albums' | 'songs';
|
||||
|
||||
/** UI opts for Advanced Search — BPM filter hidden until enrichment ships. */
|
||||
/** UI opts for Advanced Search — BPM/mood filters require local index. */
|
||||
export interface LocalSearchOpts {
|
||||
query: string;
|
||||
genre: string;
|
||||
yearFrom: string;
|
||||
yearTo: string;
|
||||
bpmFrom: string;
|
||||
bpmTo: string;
|
||||
moodGroup: string;
|
||||
resultType: AdvancedResultType;
|
||||
}
|
||||
|
||||
@@ -73,9 +77,39 @@ function buildFilters(opts: LocalSearchOpts): LibraryFilterClause[] {
|
||||
} else if (to !== null) {
|
||||
filters.push({ field: 'year', op: 'lte', value: to });
|
||||
}
|
||||
const bpmFrom = opts.bpmFrom ? parseInt(opts.bpmFrom, 10) : null;
|
||||
const bpmTo = opts.bpmTo ? parseInt(opts.bpmTo, 10) : null;
|
||||
if (bpmFrom !== null && bpmTo !== null) {
|
||||
filters.push({ field: 'bpm', op: 'between', value: bpmFrom, valueTo: bpmTo });
|
||||
} else if (bpmFrom !== null) {
|
||||
filters.push({ field: 'bpm', op: 'gte', value: bpmFrom });
|
||||
} else if (bpmTo !== null) {
|
||||
filters.push({ field: 'bpm', op: 'lte', value: bpmTo });
|
||||
}
|
||||
if (OXIMEDIA_MOOD_SEARCH_ENABLED && opts.moodGroup) {
|
||||
filters.push({ field: 'mood_group', op: 'eq', value: opts.moodGroup });
|
||||
}
|
||||
return filters;
|
||||
}
|
||||
|
||||
function applyClientSongFilters(
|
||||
list: SubsonicSong[],
|
||||
opts: LocalSearchOpts,
|
||||
): SubsonicSong[] {
|
||||
let r = list;
|
||||
const g = opts.genre;
|
||||
const from = opts.yearFrom ? parseInt(opts.yearFrom, 10) : null;
|
||||
const to = opts.yearTo ? parseInt(opts.yearTo, 10) : null;
|
||||
const bpmFrom = opts.bpmFrom ? parseInt(opts.bpmFrom, 10) : null;
|
||||
const bpmTo = opts.bpmTo ? parseInt(opts.bpmTo, 10) : null;
|
||||
if (g) r = r.filter(s => s.genre?.toLowerCase() === g.toLowerCase());
|
||||
if (from !== null) r = r.filter(s => !s.year || s.year >= from);
|
||||
if (to !== null) r = r.filter(s => !s.year || s.year <= to);
|
||||
if (bpmFrom !== null) r = r.filter(s => s.bpm != null && s.bpm > 0 && s.bpm >= bpmFrom);
|
||||
if (bpmTo !== null) r = r.filter(s => s.bpm != null && s.bpm > 0 && s.bpm <= bpmTo);
|
||||
return r;
|
||||
}
|
||||
|
||||
function buildRequest(
|
||||
serverId: string,
|
||||
opts: LocalSearchOpts,
|
||||
@@ -100,6 +134,7 @@ function buildRequest(
|
||||
|
||||
export function trackToSong(t: LibraryTrackDto): SubsonicSong {
|
||||
const raw = isObject(t.rawJson) ? t.rawJson : {};
|
||||
const resolvedBpm = t.bpm != null && t.bpm > 0 ? t.bpm : undefined;
|
||||
const base: SubsonicSong = {
|
||||
id: t.id,
|
||||
title: t.title,
|
||||
@@ -119,13 +154,18 @@ export function trackToSong(t: LibraryTrackDto): SubsonicSong {
|
||||
starred: t.starredAt != null ? new Date(t.starredAt).toISOString() : undefined,
|
||||
userRating: t.userRating ?? undefined,
|
||||
playCount: t.playCount ?? undefined,
|
||||
bpm: t.bpm ?? undefined,
|
||||
bpm: resolvedBpm,
|
||||
isrc: t.isrc ?? undefined,
|
||||
albumArtist: t.albumArtist ?? undefined,
|
||||
};
|
||||
// `rawJson` is the authoritative original song — let it override the
|
||||
// hot-column fallbacks (it carries OpenSubsonic extras too).
|
||||
return { ...base, ...(raw as Partial<SubsonicSong>) };
|
||||
const merged: SubsonicSong = { ...base, ...(raw as Partial<SubsonicSong>) };
|
||||
if (resolvedBpm != null) merged.bpm = resolvedBpm;
|
||||
if (t.bpmSource === 'analysis' || t.bpmSource === 'tag') {
|
||||
merged.localBpmSource = t.bpmSource;
|
||||
}
|
||||
return merged;
|
||||
}
|
||||
|
||||
export function albumToAlbum(a: LibraryAlbumDto): SubsonicAlbum {
|
||||
@@ -165,9 +205,6 @@ export async function runNetworkAdvancedTextSearch(
|
||||
): Promise<LocalAdvancedSearchPage | null> {
|
||||
const q = opts.query.trim();
|
||||
if (!q) return null;
|
||||
const g = opts.genre;
|
||||
const from = opts.yearFrom ? parseInt(opts.yearFrom, 10) : null;
|
||||
const to = opts.yearTo ? parseInt(opts.yearTo, 10) : null;
|
||||
const rt = opts.resultType;
|
||||
|
||||
const r = await search(q, {
|
||||
@@ -178,12 +215,11 @@ export async function runNetworkAdvancedTextSearch(
|
||||
|
||||
let artists = r.artists;
|
||||
let albums = r.albums;
|
||||
let songs = r.songs;
|
||||
|
||||
if (g) songs = songs.filter(s => s.genre?.toLowerCase() === g.toLowerCase());
|
||||
if (from !== null) songs = songs.filter(s => !s.year || s.year >= from);
|
||||
if (to !== null) songs = songs.filter(s => !s.year || s.year <= to);
|
||||
let songs = applyClientSongFilters(r.songs, opts);
|
||||
|
||||
const g = opts.genre;
|
||||
const from = opts.yearFrom ? parseInt(opts.yearFrom, 10) : null;
|
||||
const to = opts.yearTo ? parseInt(opts.yearTo, 10) : null;
|
||||
if (g) albums = albums.filter(a => a.genre?.toLowerCase() === g.toLowerCase());
|
||||
if (from !== null) albums = albums.filter(a => !a.year || a.year >= from);
|
||||
if (to !== null) albums = albums.filter(a => !a.year || a.year <= to);
|
||||
|
||||
@@ -176,6 +176,9 @@ const emptyBrowseOpts = (query: string): LocalSearchOpts => ({
|
||||
genre: '',
|
||||
yearFrom: '',
|
||||
yearTo: '',
|
||||
bpmFrom: '',
|
||||
bpmTo: '',
|
||||
moodGroup: '',
|
||||
resultType: 'artists',
|
||||
});
|
||||
|
||||
@@ -184,6 +187,9 @@ const songBrowseOpts = (query: string): LocalSearchOpts => ({
|
||||
genre: '',
|
||||
yearFrom: '',
|
||||
yearTo: '',
|
||||
bpmFrom: '',
|
||||
bpmTo: '',
|
||||
moodGroup: '',
|
||||
resultType: 'songs',
|
||||
});
|
||||
|
||||
@@ -192,6 +198,9 @@ const fullSearchOpts = (query: string): LocalSearchOpts => ({
|
||||
genre: '',
|
||||
yearFrom: '',
|
||||
yearTo: '',
|
||||
bpmFrom: '',
|
||||
bpmTo: '',
|
||||
moodGroup: '',
|
||||
resultType: 'all',
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import type { TFunction } from 'i18next';
|
||||
import {
|
||||
deriveMoodScores,
|
||||
formatQueueBpmTech,
|
||||
formatQueueMoodLabels,
|
||||
parseTrackEnrichmentFacts,
|
||||
resolveQueueBpm,
|
||||
resolveDisplayBpm,
|
||||
topMoodLabelIds,
|
||||
} from './trackEnrichment';
|
||||
import { topDistinctOximediaMoodTagIds, topOximediaMoodTagIds } from '../../config/moodGroups';
|
||||
|
||||
const t = ((key: string, opts?: Record<string, unknown>) => {
|
||||
if (key === 'queue.bpm') return `${opts?.bpm} BPM`;
|
||||
if (key === 'queue.moods.calm') return 'Calm';
|
||||
if (key === 'queue.moods.peaceful') return 'Peaceful';
|
||||
return key;
|
||||
}) as TFunction;
|
||||
|
||||
describe('parseTrackEnrichmentFacts', () => {
|
||||
it('does not surface oximedia mood labels in UI while detector is disabled', () => {
|
||||
const parsed = parseTrackEnrichmentFacts(
|
||||
[
|
||||
{
|
||||
serverId: 's1',
|
||||
trackId: 't1',
|
||||
factKind: 'moods',
|
||||
sourceKind: 'analysis',
|
||||
sourceId: 'oximedia-60s-center',
|
||||
valueText: '{"calm":0.6,"peaceful":0.4}',
|
||||
confidence: 0.9,
|
||||
fetchedAt: 1,
|
||||
},
|
||||
{
|
||||
serverId: 's1',
|
||||
trackId: 't1',
|
||||
factKind: 'valence',
|
||||
sourceKind: 'analysis',
|
||||
sourceId: 'oximedia-60s-center',
|
||||
valueReal: 0.55,
|
||||
confidence: 0.9,
|
||||
fetchedAt: 1,
|
||||
},
|
||||
{
|
||||
serverId: 's1',
|
||||
trackId: 't1',
|
||||
factKind: 'arousal',
|
||||
sourceKind: 'analysis',
|
||||
sourceId: 'oximedia-60s-center',
|
||||
valueReal: 0.42,
|
||||
confidence: 0.9,
|
||||
fetchedAt: 1,
|
||||
},
|
||||
],
|
||||
null,
|
||||
);
|
||||
expect(parsed.moodLabels).toEqual([]);
|
||||
});
|
||||
|
||||
it('reads analysis bpm fact with highest confidence', () => {
|
||||
const parsed = parseTrackEnrichmentFacts(
|
||||
[
|
||||
{
|
||||
serverId: 's1',
|
||||
trackId: 't1',
|
||||
factKind: 'bpm',
|
||||
sourceKind: 'analysis',
|
||||
sourceId: 'oximedia-60s-center',
|
||||
valueInt: 128,
|
||||
confidence: 0.9,
|
||||
fetchedAt: 1,
|
||||
},
|
||||
{
|
||||
serverId: 's1',
|
||||
trackId: 't1',
|
||||
factKind: 'bpm',
|
||||
sourceKind: 'analysis',
|
||||
sourceId: 'other',
|
||||
valueInt: 110,
|
||||
confidence: 0.5,
|
||||
fetchedAt: 1,
|
||||
},
|
||||
],
|
||||
120,
|
||||
);
|
||||
expect(parsed.measuredBpm).toBe(128);
|
||||
expect(parsed.serverBpm).toBe(120);
|
||||
expect(resolveQueueBpm(parsed)).toBe(128);
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveQueueBpm', () => {
|
||||
it('prefers measured analysis bpm over tag', () => {
|
||||
expect(resolveQueueBpm({ serverBpm: 120, measuredBpm: 128, moodLabels: [] })).toBe(128);
|
||||
});
|
||||
|
||||
it('falls back to tag bpm when no analysis fact', () => {
|
||||
expect(resolveQueueBpm({ serverBpm: 120, measuredBpm: null, moodLabels: [] })).toBe(120);
|
||||
});
|
||||
|
||||
it('falls back to measured when tag bpm missing', () => {
|
||||
expect(resolveQueueBpm({ serverBpm: null, measuredBpm: 128, moodLabels: [] })).toBe(128);
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveDisplayBpm', () => {
|
||||
it('ignores zero tag bpm and uses measured', () => {
|
||||
expect(resolveDisplayBpm(0, 132)).toBe(132);
|
||||
});
|
||||
});
|
||||
|
||||
describe('formatters', () => {
|
||||
it('formats bpm for tech row', () => {
|
||||
expect(formatQueueBpmTech({ serverBpm: 120, measuredBpm: 128, moodLabels: [] }, t)).toBe('128 BPM');
|
||||
});
|
||||
|
||||
it('localizes mood labels without weights', () => {
|
||||
expect(formatQueueMoodLabels(['calm', 'peaceful'], t)).toBe('Calm · Peaceful');
|
||||
});
|
||||
});
|
||||
|
||||
describe('topMoodLabelIds', () => {
|
||||
it('returns at most two distinct cluster labels from valence/arousal', () => {
|
||||
const labels = topMoodLabelIds(0.4, 0.75);
|
||||
expect(labels.includes('happy') && labels.includes('excited')).toBe(false);
|
||||
expect(labels.length).toBeLessThanOrEqual(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('distinct mood tag picking', () => {
|
||||
it('never keeps both happy and excited from raw scores', () => {
|
||||
expect(topDistinctOximediaMoodTagIds({ calm: 0.52, happy: 0.9, excited: 0.5 })).toEqual(['happy', 'calm']);
|
||||
});
|
||||
|
||||
it('sorts by score descending with id tie-break', () => {
|
||||
expect(topOximediaMoodTagIds({ calm: 0.2, happy: 0.9, excited: 0.5 })).toEqual([
|
||||
'happy',
|
||||
'excited',
|
||||
'calm',
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('deriveMoodScores', () => {
|
||||
it('delegates to soft valence/arousal scoring', () => {
|
||||
const scores = deriveMoodScores(0.55, 0.42);
|
||||
expect(topDistinctOximediaMoodTagIds(scores, 2).some(id => id === 'calm' || id === 'peaceful')).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,163 @@
|
||||
import type { TFunction } from 'i18next';
|
||||
import type { TrackFactDto } from '../../api/library';
|
||||
import {
|
||||
distinctOximediaMoodTagIds,
|
||||
topDistinctOximediaMoodTagIds,
|
||||
topDistinctOximediaMoodTagIdsFromValenceArousal,
|
||||
moodScoresFromValenceArousal,
|
||||
} from '../../config/moodGroups';
|
||||
|
||||
/** Oximedia mood labels in queue/Song Info — off until a reliable model ships. */
|
||||
export const OXIMEDIA_MOOD_UI_ENABLED = false;
|
||||
/** Mood group filter in Advanced Search — off while oximedia mood is disabled. */
|
||||
export const OXIMEDIA_MOOD_SEARCH_ENABLED = false;
|
||||
export const OXIMEDIA_ENRICHMENT_SOURCE_KIND = 'analysis';
|
||||
export const OXIMEDIA_ENRICHMENT_SOURCE_ID = 'oximedia-60s-center';
|
||||
|
||||
/** Oximedia mood label ids — see `src/config/moodGroups.ts` and Rust `mood_groups`. */
|
||||
export type { OximediaMoodTagId } from '../../config/moodGroups';
|
||||
|
||||
export interface ParsedTrackEnrichment {
|
||||
serverBpm: number | null;
|
||||
measuredBpm: number | null;
|
||||
moodLabels: string[];
|
||||
}
|
||||
|
||||
function isOximediaFact(f: TrackFactDto): boolean {
|
||||
return (
|
||||
f.sourceKind === OXIMEDIA_ENRICHMENT_SOURCE_KIND
|
||||
&& (f.sourceId === OXIMEDIA_ENRICHMENT_SOURCE_ID
|
||||
|| f.sourceId.startsWith(`${OXIMEDIA_ENRICHMENT_SOURCE_ID}:`))
|
||||
);
|
||||
}
|
||||
|
||||
function pickBestAnalysisBpmFact(facts: readonly TrackFactDto[]): TrackFactDto | undefined {
|
||||
let best: TrackFactDto | undefined;
|
||||
for (const f of facts) {
|
||||
if (f.factKind !== 'bpm') continue;
|
||||
if (f.sourceKind !== 'analysis') continue;
|
||||
if (f.valueInt == null || f.valueInt <= 0) continue;
|
||||
if (!best || (f.confidence ?? 0) > (best.confidence ?? 0)) best = f;
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
export function parseTrackEnrichmentFacts(
|
||||
facts: readonly TrackFactDto[],
|
||||
serverBpm: number | null | undefined,
|
||||
): ParsedTrackEnrichment {
|
||||
const oximedia = facts.filter(isOximediaFact);
|
||||
const measured = pickBestAnalysisBpmFact(facts);
|
||||
const moodsFact = oximedia.find(f => f.factKind === 'moods' && f.valueText);
|
||||
const legacyLabelsFact = oximedia.find(f => f.factKind === 'mood_labels' && f.valueText);
|
||||
const moodTagFacts = facts.filter(
|
||||
f => isOximediaFact(f) && f.factKind === 'mood_tag' && f.valueText,
|
||||
);
|
||||
const valence = oximedia.find(f => f.factKind === 'valence')?.valueReal ?? null;
|
||||
const arousal = oximedia.find(f => f.factKind === 'arousal')?.valueReal ?? null;
|
||||
|
||||
const hotBpm = serverBpm != null && serverBpm > 0 ? serverBpm : null;
|
||||
|
||||
const fromMoodsJson = topDistinctOximediaMoodTagIds(parseMoodsScoresJson(moodsFact?.valueText));
|
||||
const fromLegacy = parseMoodLabelsArray(legacyLabelsFact?.valueText);
|
||||
const fromMoodTags = distinctOximediaMoodTagIds(
|
||||
moodTagFacts.map(f => f.valueText!).filter(Boolean),
|
||||
);
|
||||
const fromValenceArousal =
|
||||
valence != null && arousal != null
|
||||
? topDistinctOximediaMoodTagIdsFromValenceArousal(valence, arousal)
|
||||
: [];
|
||||
const rawMoodLabels =
|
||||
(fromValenceArousal.length > 0 ? fromValenceArousal : null)
|
||||
?? (fromMoodTags.length > 0 ? fromMoodTags : null)
|
||||
?? (fromMoodsJson.length > 0 ? fromMoodsJson : null)
|
||||
?? (fromLegacy && fromLegacy.length > 0 ? fromLegacy : null)
|
||||
?? [];
|
||||
const moodLabels = OXIMEDIA_MOOD_UI_ENABLED ? rawMoodLabels : [];
|
||||
|
||||
return {
|
||||
serverBpm: hotBpm,
|
||||
measuredBpm: measured?.valueInt ?? null,
|
||||
moodLabels,
|
||||
};
|
||||
}
|
||||
|
||||
function parseMoodsScoresJson(raw: string | null | undefined): Record<string, number> | null {
|
||||
if (!raw) return null;
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(raw);
|
||||
if (typeof parsed !== 'object' || parsed == null || Array.isArray(parsed)) return null;
|
||||
const out: Record<string, number> = {};
|
||||
for (const [key, value] of Object.entries(parsed as Record<string, unknown>)) {
|
||||
if (typeof value === 'number' && Number.isFinite(value)) out[key] = value;
|
||||
}
|
||||
return Object.keys(out).length > 0 ? out : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function parseMoodLabelsArray(raw: string | null | undefined): string[] | null {
|
||||
if (!raw) return null;
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(raw);
|
||||
if (!Array.isArray(parsed)) return null;
|
||||
const labels = parsed.filter((v): v is string => typeof v === 'string' && v.length > 0);
|
||||
return labels.length > 0 ? labels.slice(0, 3) : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** @deprecated Use `moodScoresFromValenceArousal` — oximedia quadrant copy. */
|
||||
export function deriveMoodScores(valence: number, arousal: number): Record<string, number> {
|
||||
return moodScoresFromValenceArousal(valence, arousal);
|
||||
}
|
||||
|
||||
/** @deprecated Use `topDistinctOximediaMoodTagIdsFromValenceArousal`. */
|
||||
export { topDistinctOximediaMoodTagIdsFromValenceArousal as topMoodLabelIds } from '../../config/moodGroups';
|
||||
|
||||
/** Analysis/measured BPM when present; otherwise file tag BPM. */
|
||||
export function resolveDisplayBpm(
|
||||
tagBpm: number | null | undefined,
|
||||
measuredBpm: number | null | undefined,
|
||||
): number | null {
|
||||
if (measuredBpm != null && measuredBpm > 0) return measuredBpm;
|
||||
if (tagBpm != null && tagBpm > 0) return tagBpm;
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Analysis fact wins; tag BPM is shown until a fact is stored. */
|
||||
export function resolveQueueBpm(data: ParsedTrackEnrichment): number | null {
|
||||
return resolveDisplayBpm(data.serverBpm, data.measuredBpm);
|
||||
}
|
||||
|
||||
export function formatQueueBpmTech(data: ParsedTrackEnrichment, t: TFunction): string | null {
|
||||
const bpm = resolveQueueBpm(data);
|
||||
if (bpm == null) return null;
|
||||
return t('queue.bpm', { bpm });
|
||||
}
|
||||
|
||||
export function formatQueueMoodLabels(labels: readonly string[], t: TFunction): string | null {
|
||||
const names = labels
|
||||
.slice(0, 3)
|
||||
.map(id => {
|
||||
const key = `queue.moods.${id}`;
|
||||
const translated = t(key);
|
||||
return translated === key ? id : translated;
|
||||
});
|
||||
return names.length > 0 ? names.join(' · ') : null;
|
||||
}
|
||||
|
||||
function enrichmentHasMoodLabels(data: ParsedTrackEnrichment): boolean {
|
||||
return data.moodLabels.length > 0;
|
||||
}
|
||||
|
||||
function enrichmentHasBpm(data: ParsedTrackEnrichment): boolean {
|
||||
return (data.measuredBpm != null && data.measuredBpm > 0)
|
||||
|| (data.serverBpm != null && data.serverBpm > 0);
|
||||
}
|
||||
|
||||
export function enrichmentDisplayComplete(data: ParsedTrackEnrichment): boolean {
|
||||
return enrichmentHasMoodLabels(data) || enrichmentHasBpm(data);
|
||||
}
|
||||
Reference in New Issue
Block a user