mirror of
https://github.com/pvrzz/atmosphere.git
synced 2026-11-29 05:22:26 +00:00
Artist photos, bios and logos from keyless public sources
- Photos from Deezer's public artist search (exact name match, most-followed artist) - Bios from Wikipedia when the page is about a musician or band, credited under CC BY-SA - Logos from Wikidata, kept as transparent PNGs; dark logos are flipped on dark banners - Only fills what's empty; anything you set or remove yourself stays - Edit artist: photo, logo, bio, remove any of them, or look them up again - Runs quietly in the background, and right away when you open an artist - Can be turned off in Settings, Library
This commit is contained in:
@@ -0,0 +1,168 @@
|
||||
// atmosphere · artistinfo.rs · Finds artist photos, bios and logos from keyless public sources: Deezer, Wikipedia and Wikidata
|
||||
use anyhow::Result;
|
||||
use regex::Regex;
|
||||
use serde_json::Value;
|
||||
use std::sync::LazyLock;
|
||||
use std::time::Duration;
|
||||
|
||||
const MAX_IMAGE: usize = 8 * 1024 * 1024;
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Found {
|
||||
pub photo: Option<Vec<u8>>,
|
||||
pub bio: Option<String>,
|
||||
pub bio_source: Option<String>,
|
||||
pub logo: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
pub fn norm(s: &str) -> String {
|
||||
s.chars().filter(|c| c.is_alphanumeric()).flat_map(char::to_lowercase).collect()
|
||||
}
|
||||
|
||||
static MUSIC: LazyLock<Regex> = LazyLock::new(|| {
|
||||
Regex::new(r"(?i)\b(singer|rapper|musician|band|group|duo|trio|dj|disc jockey|producer|songwriter|composer|vocalist|guitarist|pianist|drummer|music|hip[- ]hop|rock|pop|electronic|orchestra|ensemble|artist)\b").unwrap()
|
||||
});
|
||||
|
||||
pub fn is_music_description(d: &str) -> bool {
|
||||
MUSIC.is_match(d) && !Regex::new(r"(?i)\b(album|song|single|ep|discography|film|episode|video game)\b").unwrap().is_match(d.split(" by ").next().unwrap_or(d))
|
||||
}
|
||||
|
||||
fn title_matches(key: &str, name: &str) -> bool {
|
||||
let title = key.replace('_', " ");
|
||||
let base = title.split(" (").next().unwrap_or(&title);
|
||||
norm(base) == norm(name)
|
||||
}
|
||||
|
||||
async fn get_json(http: &reqwest::Client, url: &str) -> Option<Value> {
|
||||
let r = http.get(url).timeout(Duration::from_secs(15)).send().await.ok()?;
|
||||
if !r.status().is_success() {
|
||||
return None;
|
||||
}
|
||||
r.json().await.ok()
|
||||
}
|
||||
|
||||
async fn get_bytes(http: &reqwest::Client, url: &str) -> Option<Vec<u8>> {
|
||||
let r = http.get(url).timeout(Duration::from_secs(20)).send().await.ok()?;
|
||||
if !r.status().is_success() || r.content_length().is_some_and(|n| n as usize > MAX_IMAGE) {
|
||||
return None;
|
||||
}
|
||||
let b = r.bytes().await.ok()?;
|
||||
(b.len() <= MAX_IMAGE && !b.is_empty()).then(|| b.to_vec())
|
||||
}
|
||||
|
||||
fn enc(s: &str) -> String {
|
||||
url::form_urlencoded::byte_serialize(s.as_bytes()).collect()
|
||||
}
|
||||
|
||||
fn path_enc(s: &str) -> String {
|
||||
s.replace(' ', "_")
|
||||
.bytes()
|
||||
.map(|b| if b.is_ascii_alphanumeric() || b"-_.~()".contains(&b) { (b as char).to_string() } else { format!("%{b:02X}") })
|
||||
.collect()
|
||||
}
|
||||
|
||||
async fn deezer_photo(http: &reqwest::Client, name: &str) -> Option<Vec<u8>> {
|
||||
let v = get_json(http, &format!("https://api.deezer.com/search/artist?q={}&limit=8", enc(name))).await?;
|
||||
let want = norm(name);
|
||||
let best = v["data"]
|
||||
.as_array()?
|
||||
.iter()
|
||||
.filter(|a| a["name"].as_str().is_some_and(|n| norm(n) == want))
|
||||
.filter(|a| a["picture_xl"].as_str().is_some_and(|u| !u.contains("/artist//")))
|
||||
.max_by_key(|a| a["nb_fan"].as_u64().unwrap_or(0))?;
|
||||
get_bytes(http, best["picture_xl"].as_str()?).await
|
||||
}
|
||||
|
||||
async fn wikipedia(http: &reqwest::Client, name: &str) -> Option<(String, String, Option<String>)> {
|
||||
let v = get_json(http, &format!("https://en.wikipedia.org/w/rest.php/v1/search/page?q={}&limit=10", enc(name))).await?;
|
||||
let pages = v["pages"].as_array()?;
|
||||
let pick = pages
|
||||
.iter()
|
||||
.filter(|p| p["key"].as_str().is_some_and(|k| title_matches(k, name)))
|
||||
.find(|p| p["description"].as_str().is_some_and(is_music_description))?;
|
||||
let key = pick["key"].as_str()?;
|
||||
let s = get_json(http, &format!("https://en.wikipedia.org/api/rest_v1/page/summary/{}", path_enc(key))).await?;
|
||||
if s["type"].as_str() != Some("standard") {
|
||||
return None;
|
||||
}
|
||||
let extract = s["extract"].as_str()?.trim().to_string();
|
||||
if extract.len() < 40 {
|
||||
return None;
|
||||
}
|
||||
let url = s["content_urls"]["desktop"]["page"].as_str().unwrap_or_default().to_string();
|
||||
Some((extract, url, s["wikibase_item"].as_str().map(String::from)))
|
||||
}
|
||||
|
||||
async fn wikidata_file(http: &reqwest::Client, qid: &str, prop: &str) -> Option<Vec<u8>> {
|
||||
if !qid.starts_with('Q') || !qid[1..].chars().all(|c| c.is_ascii_digit()) {
|
||||
return None;
|
||||
}
|
||||
let v = get_json(http, &format!("https://www.wikidata.org/wiki/Special:EntityData/{qid}.json")).await?;
|
||||
let file = v["entities"][qid]["claims"][prop][0]["mainsnak"]["datavalue"]["value"].as_str()?;
|
||||
get_bytes(http, &format!("https://commons.wikimedia.org/wiki/Special:FilePath/{}?width=800", path_enc(file))).await
|
||||
}
|
||||
|
||||
pub async fn find(http: &reqwest::Client, name: &str, want_photo: bool, want_bio: bool, want_logo: bool) -> Result<Found> {
|
||||
let mut found = Found::default();
|
||||
let photo = async {
|
||||
if want_photo {
|
||||
deezer_photo(http, name).await
|
||||
} else {
|
||||
None
|
||||
}
|
||||
};
|
||||
let wiki = async {
|
||||
if want_bio || want_logo || want_photo {
|
||||
wikipedia(http, name).await
|
||||
} else {
|
||||
None
|
||||
}
|
||||
};
|
||||
let (photo, wiki) = tokio::join!(photo, wiki);
|
||||
found.photo = photo;
|
||||
if let Some((bio, url, qid)) = wiki {
|
||||
if want_bio {
|
||||
found.bio = Some(bio);
|
||||
found.bio_source = Some(url);
|
||||
}
|
||||
if let Some(q) = qid {
|
||||
if want_logo {
|
||||
found.logo = wikidata_file(http, &q, "P154").await;
|
||||
}
|
||||
if want_photo && found.photo.is_none() {
|
||||
found.photo = wikidata_file(http, &q, "P18").await;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(found)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn matches_names_and_music_pages_only() {
|
||||
assert!(title_matches("Daft_Punk", "Daft Punk"));
|
||||
assert!(title_matches("Nirvana_(band)", "Nirvana"));
|
||||
assert!(!title_matches("Discovery_(Daft_Punk_album)", "Daft Punk"));
|
||||
assert!(is_music_description("French electronic music duo (1993–2021)"));
|
||||
assert!(is_music_description("American rapper and singer"));
|
||||
assert!(!is_music_description("2001 studio album by Daft Punk"));
|
||||
assert!(!is_music_description("City in France"));
|
||||
assert_eq!(norm("Kühvt!"), "kühvt");
|
||||
assert_eq!(path_enc("Daft Punk logo.svg"), "Daft_Punk_logo.svg");
|
||||
assert_eq!(path_enc("Beyoncé"), "Beyonc%C3%A9");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore]
|
||||
async fn live_finds_daft_punk() {
|
||||
let http = reqwest::Client::builder().user_agent("Atmosphere/test (desktop music player)").build().unwrap();
|
||||
let f = find(&http, "Daft Punk", true, true, true).await.unwrap();
|
||||
assert!(f.photo.is_some_and(|p| p.len() > 10_000));
|
||||
assert!(f.bio.is_some_and(|b| b.contains("Daft Punk")));
|
||||
assert!(f.bio_source.is_some_and(|u| u.contains("wikipedia.org")));
|
||||
assert!(f.logo.is_some());
|
||||
}
|
||||
}
|
||||
@@ -499,6 +499,10 @@ pub fn serve(app: &AppHandle, request: &Request<Vec<u8>>) -> Response<Vec<u8>> {
|
||||
None => respond(404, "text/plain", b"unknown track".to_vec(), &[]),
|
||||
},
|
||||
"a" => match state.library.art_path(id) {
|
||||
Some(p) if p.extension().is_some_and(|e| e == "png") => match std::fs::read(&p) {
|
||||
Ok(data) => respond(200, "image/png", data, &[("Cache-Control", "max-age=86400".into())]),
|
||||
Err(_) => respond(404, "text/plain", Vec::new(), &[]),
|
||||
},
|
||||
Some(p) => {
|
||||
let data = std::fs::read(&p).unwrap_or_default();
|
||||
respond(200, "image/jpeg", data, &[("Cache-Control", "max-age=86400".into())])
|
||||
@@ -613,3 +617,38 @@ pub fn playlist_cover(app: AppHandle, state: State<'_, AppState>, name: String,
|
||||
changed(&app);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn artist_fetch(state: State<'_, AppState>, name: String, force: bool) -> CmdResult<Option<crate::library::ArtistMeta>> {
|
||||
let s = state.snapshot();
|
||||
if !s.artist_info && !force {
|
||||
return Ok(None);
|
||||
}
|
||||
let existing = state.library.artist(&name).unwrap_or_default();
|
||||
if existing.checked.is_some() && !force {
|
||||
return Ok(Some(existing));
|
||||
}
|
||||
let want_photo = force || existing.image.is_none();
|
||||
let want_bio = force || existing.bio.trim().is_empty();
|
||||
let want_logo = force || existing.logo.is_none();
|
||||
let found = crate::artistinfo::find(&state.http, &name, want_photo, want_bio, want_logo).await.map_err(err)?;
|
||||
Ok(Some(state.library.apply_artist_info(&name, found, force)))
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn artist_media(app: AppHandle, state: State<'_, AppState>, name: String, kind: String, pick: bool) -> CmdResult<crate::library::ArtistMeta> {
|
||||
let image = if pick {
|
||||
let a = app.clone();
|
||||
let title = if kind == "logo" { "Choose a logo (a transparent PNG looks best)" } else { "Choose an image" };
|
||||
let picked = tauri::async_runtime::spawn_blocking(move || a.dialog().file().set_title(title).add_filter("Images", &["png", "jpg", "jpeg", "webp"]).blocking_pick_file())
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
match picked.and_then(|p| p.into_path().ok()) {
|
||||
Some(p) => Some(p),
|
||||
None => return Err("cancelled".into()),
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
state.library.artist_media(&name, &kind, image.as_deref()).map_err(err)
|
||||
}
|
||||
|
||||
+90
-2
@@ -73,6 +73,31 @@ pub struct ArtistMeta {
|
||||
pub name: String,
|
||||
pub image: Option<String>,
|
||||
pub bio: String,
|
||||
pub bio_source: Option<String>,
|
||||
pub logo: Option<String>,
|
||||
pub logo_dark: bool,
|
||||
pub checked: Option<u64>,
|
||||
}
|
||||
|
||||
fn save_logo(key: &str, data: &[u8]) -> Option<(String, bool)> {
|
||||
let dir = art_dir();
|
||||
std::fs::create_dir_all(&dir).ok()?;
|
||||
let img = image::load_from_memory(data).ok()?;
|
||||
let img = if img.width() > 800 { img.thumbnail(800, 400) } else { img };
|
||||
let rgba = img.to_rgba8();
|
||||
let (mut sum, mut n) = (0f64, 0f64);
|
||||
for p in rgba.pixels() {
|
||||
let a = p[3] as f64 / 255.0;
|
||||
if a > 0.3 {
|
||||
sum += (0.2126 * p[0] as f64 + 0.7152 * p[1] as f64 + 0.0722 * p[2] as f64) / 255.0 * a;
|
||||
n += a;
|
||||
}
|
||||
}
|
||||
let dark = n > 0.0 && sum / n < 0.35;
|
||||
let mut buf = std::io::Cursor::new(Vec::new());
|
||||
rgba.write_to(&mut buf, image::ImageFormat::Png).ok()?;
|
||||
std::fs::write(dir.join(format!("{key}.png")), buf.into_inner()).ok()?;
|
||||
Some((key.to_string(), dark))
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
@@ -284,8 +309,7 @@ impl Library {
|
||||
|
||||
pub fn art_path(&self, key: &str) -> Option<PathBuf> {
|
||||
let safe: String = key.chars().filter(|c| c.is_ascii_alphanumeric()).collect();
|
||||
let p = art_dir().join(format!("{safe}.jpg"));
|
||||
p.exists().then_some(p)
|
||||
["jpg", "png"].iter().map(|ext| art_dir().join(format!("{safe}.{ext}"))).find(|p| p.exists())
|
||||
}
|
||||
|
||||
pub fn scan(&self, roots: &[PathBuf], playlists_dir: &Path, mut progress: impl FnMut(usize, usize)) -> Result<usize> {
|
||||
@@ -800,6 +824,9 @@ impl Library {
|
||||
meta.image = Some(save_art(&id, &data).ok_or_else(|| anyhow!("That image couldn't be read"))?);
|
||||
}
|
||||
if let Some(b) = bio {
|
||||
if b.trim() != meta.bio.trim() {
|
||||
meta.bio_source = None;
|
||||
}
|
||||
meta.bio = b;
|
||||
}
|
||||
let out = meta.clone();
|
||||
@@ -807,6 +834,67 @@ impl Library {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
pub fn artist(&self, name: &str) -> Option<ArtistMeta> {
|
||||
self.artists.read().unwrap().get(&artist_key(name)).cloned()
|
||||
}
|
||||
|
||||
pub fn apply_artist_info(&self, name: &str, found: crate::artistinfo::Found, force: bool) -> ArtistMeta {
|
||||
let key = artist_key(name);
|
||||
let mut artists = self.artists.write().unwrap();
|
||||
let meta = artists.entry(key.clone()).or_default();
|
||||
meta.name = name.trim().to_string();
|
||||
if let Some(photo) = found.photo.filter(|_| force || meta.image.is_none()) {
|
||||
let id = format!("artistweb{key}");
|
||||
let _ = std::fs::remove_file(art_dir().join(format!("{id}.jpg")));
|
||||
if let Some(k) = save_art(&id, &photo) {
|
||||
meta.image = Some(k);
|
||||
}
|
||||
}
|
||||
if let Some(bio) = found.bio.filter(|_| force || meta.bio.trim().is_empty()) {
|
||||
meta.bio = bio;
|
||||
meta.bio_source = found.bio_source;
|
||||
}
|
||||
if let Some(logo) = found.logo.filter(|_| force || meta.logo.is_none()) {
|
||||
if let Some((k, dark)) = save_logo(&format!("logo{key}"), &logo) {
|
||||
meta.logo = Some(k);
|
||||
meta.logo_dark = dark;
|
||||
}
|
||||
}
|
||||
meta.checked = Some(now());
|
||||
let out = meta.clone();
|
||||
store("artists.json", &*artists);
|
||||
out
|
||||
}
|
||||
|
||||
pub fn artist_media(&self, name: &str, kind: &str, image: Option<&Path>) -> Result<ArtistMeta> {
|
||||
let key = artist_key(name);
|
||||
let mut artists = self.artists.write().unwrap();
|
||||
let meta = artists.entry(key.clone()).or_default();
|
||||
meta.name = name.trim().to_string();
|
||||
meta.checked.get_or_insert(now());
|
||||
match (kind, image) {
|
||||
("photo", None) => meta.image = None,
|
||||
("logo", None) => {
|
||||
meta.logo = None;
|
||||
meta.logo_dark = false;
|
||||
}
|
||||
("bio", None) => {
|
||||
meta.bio.clear();
|
||||
meta.bio_source = None;
|
||||
}
|
||||
("logo", Some(src)) => {
|
||||
let data = std::fs::read(src).context("Couldn't read that image")?;
|
||||
let (k, dark) = save_logo(&format!("logouser{key}"), &data).ok_or_else(|| anyhow!("That image couldn't be read"))?;
|
||||
meta.logo = Some(k);
|
||||
meta.logo_dark = dark;
|
||||
}
|
||||
_ => bail!("Unknown artist field"),
|
||||
}
|
||||
let out = meta.clone();
|
||||
store("artists.json", &*artists);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
pub fn playlist_cover(&self, dir: &Path, name: &str, image: Option<&Path>) -> Result<()> {
|
||||
let folder = self.folder(dir, name);
|
||||
if !folder.is_dir() {
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
||||
|
||||
mod api;
|
||||
mod artistinfo;
|
||||
mod backup;
|
||||
mod direct;
|
||||
mod downloader;
|
||||
@@ -534,6 +535,8 @@ fn main() {
|
||||
libcmd::playlist_link,
|
||||
libcmd::track_loudness,
|
||||
libcmd::tracks_edit,
|
||||
libcmd::artist_fetch,
|
||||
libcmd::artist_media,
|
||||
libcmd::playlist_cover,
|
||||
libcmd::playlist_relocate,
|
||||
libcmd::playlist_unlink
|
||||
|
||||
+4
-1
@@ -62,6 +62,7 @@ pub struct Settings {
|
||||
pub cookies_file: String,
|
||||
pub api_enabled: bool,
|
||||
pub check_updates: bool,
|
||||
pub artist_info: bool,
|
||||
pub api_port: u16,
|
||||
pub api_read: bool,
|
||||
pub api_control: bool,
|
||||
@@ -108,6 +109,7 @@ impl Default for Settings {
|
||||
cookies_file: String::new(),
|
||||
api_enabled: false,
|
||||
check_updates: true,
|
||||
artist_info: true,
|
||||
api_port: 47823,
|
||||
api_read: true,
|
||||
api_control: true,
|
||||
@@ -152,6 +154,7 @@ pub struct SettingsPatch {
|
||||
pub cookies_file: Option<String>,
|
||||
pub api_enabled: Option<bool>,
|
||||
pub check_updates: Option<bool>,
|
||||
pub artist_info: Option<bool>,
|
||||
pub api_port: Option<u16>,
|
||||
pub api_read: Option<bool>,
|
||||
pub api_control: Option<bool>,
|
||||
@@ -204,7 +207,7 @@ impl Settings {
|
||||
($($f:ident),*) => { $( if let Some(v) = p.$f { self.$f = v; } )* };
|
||||
}
|
||||
set!(save_as, embed_metadata, collection_folders, number_tracks, skip_downloaded, sponsorblock, embed_subtitles, embed_chapters, watch_clipboard);
|
||||
set!(api_enabled, api_read, api_control, api_links, check_updates);
|
||||
set!(api_enabled, api_read, api_control, api_links, check_updates, artist_info);
|
||||
if let Some(p) = p.api_port.filter(|p| *p >= 1024) {
|
||||
self.api_port = p;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user