feat: add canonical artist name normalization

- Add canonical_name column to artist_images table (migration)
- Store canonical names from Qobuz when fetching artist images
- Display canonical names (properly capitalized) in artist views
- Group and sort artists by canonical name when available
- Source priority: Qobuz -> Discogs -> Metadata

This ensures "Alice in chains" displays as "Alice In Chains" based on
Qobuz's authoritative naming.
This commit is contained in:
vicrodh committed 2026-01-23 01:35:55 -06:00
1 parent 223cf481f1
commit 66d6ffb6ed
6 files changed
+127 -24

No files matched your search

+1
View File
@@ -548,6 +548,7 @@ pub fn run() {
library::commands::library_get_artist_images,
library::commands::library_cache_artist_image,
library::commands::library_set_custom_artist_image,
library::commands::library_get_canonical_names,
// Playlist local content analysis commands (offline mode)
library::commands::playlist_analyze_local_content,
library::commands::playlist_get_local_content_status,
+20 -3
View File
@@ -1570,6 +1570,7 @@ pub struct ArtistImageInfo {
pub image_url: Option<String>,
pub source: Option<String>,
pub custom_image_path: Option<String>,
pub canonical_name: Option<String>,
}
/// Get cached artist image
@@ -1598,17 +1599,33 @@ pub async fn library_get_artist_images(
Ok(results)
}
/// Cache artist image from Qobuz
/// Get all canonical artist names mapping
#[tauri::command]
pub async fn library_get_canonical_names(
state: State<'_, LibraryState>,
) -> Result<std::collections::HashMap<String, String>, String> {
let db = state.db.lock().await;
db.get_all_canonical_names().map_err(|e| e.to_string())
}
/// Cache artist image from Qobuz/Discogs with canonical name
#[tauri::command]
pub async fn library_cache_artist_image(
artist_name: String,
image_url: String,
source: String,
canonical_name: Option<String>,
state: State<'_, LibraryState>,
) -> Result<(), String> {
let db = state.db.lock().await;
db.cache_artist_image(&artist_name, Some(&image_url), &source, None)
.map_err(|e| e.to_string())
db.cache_artist_image_with_canonical(
&artist_name,
Some(&image_url),
&source,
None,
canonical_name.as_deref(),
)
.map_err(|e| e.to_string())
}
/// Set custom artist image
+54 -5
View File
@@ -486,6 +486,23 @@ impl LibraryDatabase {
log::info!("Migration completed: sample_rate is now REAL");
}
// Migration: Add canonical_name column to artist_images for artist name normalization
let has_canonical_name: bool = self.conn
.query_row(
"SELECT COUNT(*) FROM pragma_table_info('artist_images') WHERE name = 'canonical_name'",
[],
|row| row.get::<_, i32>(0),
)
.map(|count| count > 0)
.unwrap_or(false);
if !has_canonical_name {
log::info!("Running migration: adding canonical_name to artist_images");
self.conn.execute_batch(
"ALTER TABLE artist_images ADD COLUMN canonical_name TEXT;"
).map_err(|e| LibraryError::Database(format!("Migration failed: {}", e)))?;
}
Ok(())
}
@@ -2281,7 +2298,7 @@ impl LibraryDatabase {
/// Get cached artist image
pub fn get_artist_image(&self, artist_name: &str) -> Result<Option<crate::library::commands::ArtistImageInfo>, LibraryError> {
let result = self.conn.query_row(
"SELECT artist_name, image_url, source, custom_image_path FROM artist_images WHERE artist_name = ?1",
"SELECT artist_name, image_url, source, custom_image_path, canonical_name FROM artist_images WHERE artist_name = ?1",
params![artist_name],
|row| {
Ok(crate::library::commands::ArtistImageInfo {
@@ -2289,6 +2306,7 @@ impl LibraryDatabase {
image_url: row.get(1)?,
source: row.get(2)?,
custom_image_path: row.get(3)?,
canonical_name: row.get(4)?,
})
}
).optional()
@@ -2296,13 +2314,44 @@ impl LibraryDatabase {
Ok(result)
}
/// Cache artist image
/// Get all canonical artist names mapping (for bulk lookup)
pub fn get_all_canonical_names(&self) -> Result<std::collections::HashMap<String, String>, LibraryError> {
let mut stmt = self.conn.prepare(
"SELECT artist_name, canonical_name FROM artist_images WHERE canonical_name IS NOT NULL"
).map_err(|e| LibraryError::Database(format!("Failed to prepare query: {}", e)))?;
let rows = stmt.query_map([], |row| {
Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
}).map_err(|e| LibraryError::Database(format!("Failed to query canonical names: {}", e)))?;
let mut map = std::collections::HashMap::new();
for row in rows {
if let Ok((artist_name, canonical_name)) = row {
map.insert(artist_name, canonical_name);
}
}
Ok(map)
}
/// Cache artist image with optional canonical name
pub fn cache_artist_image(
&self,
artist_name: &str,
image_url: Option<&str>,
source: &str,
custom_image_path: Option<&str>,
) -> Result<(), LibraryError> {
self.cache_artist_image_with_canonical(artist_name, image_url, source, custom_image_path, None)
}
/// Cache artist image with canonical name from Qobuz/Discogs
pub fn cache_artist_image_with_canonical(
&self,
artist_name: &str,
image_url: Option<&str>,
source: &str,
custom_image_path: Option<&str>,
canonical_name: Option<&str>,
) -> Result<(), LibraryError> {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
@@ -2311,9 +2360,9 @@ impl LibraryDatabase {
self.conn.execute(
"INSERT OR REPLACE INTO artist_images
(artist_name, image_url, source, custom_image_path, fetched_at, updated_at)
VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
params![artist_name, image_url, source, custom_image_path, now, now],
(artist_name, image_url, source, custom_image_path, canonical_name, fetched_at, updated_at)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
params![artist_name, image_url, source, custom_image_path, canonical_name, now, now],
)
.map_err(|e| LibraryError::Database(format!("Failed to cache artist image: {}", e)))?;
Ok(())
@@ -227,6 +227,7 @@
<div class="artist-row">
{#each item.artists as artist (artist.name)}
{@const artistImage = artistImages.get(artist.name)}
{@const displayName = artist.displayName || artist.name}
<div
class="artist-card"
role="button"
@@ -236,7 +237,7 @@
>
<div class="artist-icon" class:has-image={!!artistImage}>
{#if artistImage}
<img src={artistImage} alt={artist.name} class="artist-image" loading="lazy" />
<img src={artistImage} alt={displayName} class="artist-image" loading="lazy" />
{:else}
<Mic2 size={32} />
{/if}
@@ -250,7 +251,7 @@
<Upload size={14} />
</button>
{/if}
<div class="artist-name">{artist.name}</div>
<div class="artist-name">{displayName}</div>
<div class="artist-stats">
{artist.album_count} albums &bull; {artist.track_count} tracks
</div>
@@ -204,6 +204,7 @@
</div>
{:else if item.type === 'artist'}
{@const artistImage = artistImages.get(item.artist.name)}
{@const displayName = item.artist.displayName || item.artist.name}
<div
class="artist-row"
role="button"
@@ -213,13 +214,13 @@
>
<div class="artist-icon" class:has-image={!!artistImage}>
{#if artistImage}
<img src={artistImage} alt={item.artist.name} loading="lazy" />
<img src={artistImage} alt={displayName} loading="lazy" />
{:else}
<Mic2 size={20} />
{/if}
</div>
<div class="artist-info">
<div class="artist-name">{item.artist.name}</div>
<div class="artist-name">{displayName}</div>
<div class="artist-stats">
{item.artist.album_count} albums &bull; {item.artist.track_count} tracks
</div>
@@ -236,21 +236,27 @@
return artists.filter(artist => artist.name.toLowerCase().includes(needle));
});
// Memoized grouped artists with alpha index
// Memoized grouped artists with alpha index and display names
let groupedArtistsMemo = $derived.by(() => {
const filtered = filteredArtistsMemo;
// Add display names from canonical names mapping
const withDisplayNames = filtered.map(artist => ({
...artist,
displayName: canonicalNames.get(artist.name) || artist.name
}));
if (!artistGroupingEnabled) {
return {
grouped: [{ key: '', id: 'ungrouped', artists: filtered }],
grouped: [{ key: '', id: 'ungrouped', artists: withDisplayNames }],
alphaGroups: new Set<string>()
};
}
// Group by first letter
const groups = new Map<string, LocalArtist[]>();
for (const artist of filtered) {
const key = alphaGroupKey(artist.name);
// Group by first letter of DISPLAY name (canonical name if available)
const groups = new Map<string, (LocalArtist & { displayName: string })[]>();
for (const artist of withDisplayNames) {
const key = alphaGroupKey(artist.displayName);
let group = groups.get(key);
if (!group) {
group = [];
@@ -269,7 +275,10 @@
const grouped = keys.map(key => ({
key,
id: `artist-alpha-${key}`,
artists: groups.get(key) ?? []
// Sort artists within group by display name
artists: (groups.get(key) ?? []).sort((a, b) =>
a.displayName.localeCompare(b.displayName)
)
}));
return {
@@ -397,6 +406,9 @@
// Qobuz artist images cache (artist name -> image URL)
let artistImages = $state<Map<string, string>>(new Map());
// Canonical artist names mapping (local name -> Qobuz/Discogs canonical name)
let canonicalNames = $state<Map<string, string>>(new Map());
// Album edit modal state
let showAlbumEditModal = $state(false);
let editingAlbumTitle = $state('');
@@ -1678,7 +1690,7 @@
}
/**
* Load cached artist images from database.
* Load cached artist images and canonical names from database.
*/
async function loadCachedArtistImages(): Promise<void> {
try {
@@ -1688,6 +1700,7 @@
image_url: string | null;
source: string | null;
custom_image_path: string | null;
canonical_name: string | null;
}>>('library_get_artist_images', { artistNames });
for (const cached of cachedImages) {
@@ -1697,14 +1710,26 @@
if (imageUrl) {
artistImages.set(cached.artist_name, imageUrl);
}
// Store canonical name if available and different
if (cached.canonical_name && cached.canonical_name !== cached.artist_name) {
canonicalNames.set(cached.artist_name, cached.canonical_name);
}
}
// Trigger re-render
artistImages = new Map(artistImages);
canonicalNames = new Map(canonicalNames);
} catch (err) {
console.debug('Failed to load cached artist images:', err);
}
}
/**
* Get the display name for an artist (canonical if available, otherwise original).
*/
function getArtistDisplayName(name: string): string {
return canonicalNames.get(name) || name;
}
/**
* Fetch missing artist images from Qobuz only (Discogs disabled due to rate limiting).
* Fetches sequentially with delays to avoid API abuse.
@@ -1774,18 +1799,26 @@
);
const match = exactMatch ?? results.items[0];
const imageUrl = match.image?.large || match.image?.thumbnail || match.image?.small;
// Store canonical name from Qobuz (properly capitalized)
const canonicalName = match.name;
if (imageUrl) {
// Cache in database
// Cache in database with canonical name
await invoke('library_cache_artist_image', {
artistName: name,
imageUrl,
source: 'qobuz'
source: 'qobuz',
canonicalName
});
artistImages.set(name, imageUrl);
// Also store canonical name mapping
if (canonicalName && canonicalName !== name) {
canonicalNames.set(name, canonicalName);
}
// Update state periodically (every 5 artists)
if (i % 5 === 4) {
artistImages = new Map(artistImages);
canonicalNames = new Map(canonicalNames);
}
}
}
@@ -2648,6 +2681,7 @@
<div class="artist-grid">
{#each filteredArtists as artist (artist.name)}
{@const artistImage = artistImages.get(artist.name)}
{@const displayName = canonicalNames.get(artist.name) || artist.name}
<div
class="artist-card"
role="button"
@@ -2657,7 +2691,7 @@
>
<div class="artist-icon" class:has-image={!!artistImage}>
{#if artistImage}
<img src={artistImage} alt={artist.name} class="artist-image" loading="lazy" />
<img src={artistImage} alt={displayName} class="artist-image" loading="lazy" />
{:else}
<Mic2 size={32} />
{/if}
@@ -2671,7 +2705,7 @@
<Upload size={14} />
</button>
{/if}
<div class="artist-name">{artist.name}</div>
<div class="artist-name">{displayName}</div>
<div class="artist-stats">
{artist.album_count} albums &bull; {artist.track_count} tracks
</div>