feat: fall back to LRCLIB when Yandex has no lyrics
Look the track up on lrclib.net by exact signature, then by search filtered on length, preferring synced lyrics. The drawer credits LRCLIB, and the empty-state message no longer names Yandex. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
4ea9250e16
commit
899ab223b9
10 files changed
+216
-20
No files matched your search
@@ -0,0 +1,170 @@
|
||||
//! LRCLIB (lrclib.net), the open lyrics database, for tracks Yandex has no lyrics for.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use serde::Deserialize;
|
||||
|
||||
use crate::edit::{Lyrics, LyricsSource};
|
||||
use crate::models::Track;
|
||||
use crate::{Error, Result};
|
||||
|
||||
const BASE: &str = "https://lrclib.net/api";
|
||||
/// LRCLIB asks clients to name themselves.
|
||||
const USER_AGENT: &str = concat!("musyx/", env!("CARGO_PKG_VERSION"));
|
||||
const TIMEOUT: Duration = Duration::from_secs(10);
|
||||
/// How far a match's length may stray from the track's; LRCLIB's own `get` uses ±2 s.
|
||||
const SLACK: f64 = 2.0;
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct Record {
|
||||
#[serde(default)]
|
||||
duration: Option<f64>,
|
||||
#[serde(default)]
|
||||
instrumental: bool,
|
||||
plain_lyrics: Option<String>,
|
||||
synced_lyrics: Option<String>,
|
||||
}
|
||||
|
||||
impl Record {
|
||||
fn has_lyrics(&self) -> bool {
|
||||
!self.instrumental && (filled(&self.synced_lyrics).is_some() || filled(&self.plain_lyrics).is_some())
|
||||
}
|
||||
|
||||
/// Synced when there are timings, else plain text.
|
||||
fn into_lyrics(self) -> Option<Lyrics> {
|
||||
if self.instrumental {
|
||||
return None;
|
||||
}
|
||||
let lyrics = match (filled(&self.synced_lyrics), filled(&self.plain_lyrics)) {
|
||||
(Some(lrc), _) => Lyrics::from_lrc(lrc, vec![]),
|
||||
(None, Some(text)) => Lyrics::from_text(text, vec![]),
|
||||
(None, None) => return None,
|
||||
};
|
||||
Some(Lyrics { source: LyricsSource::Lrclib, ..lyrics })
|
||||
}
|
||||
}
|
||||
|
||||
fn filled(s: &Option<String>) -> Option<&str> {
|
||||
s.as_deref().filter(|s| !s.trim().is_empty())
|
||||
}
|
||||
|
||||
/// Looks the track up by its exact signature first, then by a looser search
|
||||
/// filtered on length so a live cut or a remix doesn't borrow the studio timings.
|
||||
pub(crate) async fn lyrics(http: &reqwest::Client, track: &Track) -> Result<Option<Lyrics>> {
|
||||
let Some(artist) = track.artists.first().map(|a| a.name.as_str()) else { return Ok(None) };
|
||||
let secs = track.duration.as_secs_f64();
|
||||
|
||||
if let Some(album) = &track.album
|
||||
&& secs > 0.0
|
||||
{
|
||||
let duration = secs.round().to_string();
|
||||
let query = [
|
||||
("track_name", track.title.as_str()),
|
||||
("artist_name", artist),
|
||||
("album_name", album.title.as_str()),
|
||||
("duration", duration.as_str()),
|
||||
];
|
||||
if let Some(record) = get::<Record>(http, "get", &query).await?
|
||||
&& let Some(lyrics) = record.into_lyrics()
|
||||
{
|
||||
return Ok(Some(lyrics));
|
||||
}
|
||||
}
|
||||
|
||||
let query = [("track_name", track.title.as_str()), ("artist_name", artist)];
|
||||
let found = get::<Vec<Record>>(http, "search", &query).await?.unwrap_or_default();
|
||||
Ok(pick(found, secs).and_then(Record::into_lyrics))
|
||||
}
|
||||
|
||||
/// The closest-length match that has words, preferring synced ones.
|
||||
fn pick(found: Vec<Record>, secs: f64) -> Option<Record> {
|
||||
let off = |r: &Record| match r.duration {
|
||||
Some(d) if secs > 0.0 => (d - secs).abs(),
|
||||
_ => 0.0,
|
||||
};
|
||||
found
|
||||
.into_iter()
|
||||
.filter(|r| r.has_lyrics() && (secs <= 0.0 || r.duration.is_none_or(|d| (d - secs).abs() <= SLACK)))
|
||||
.min_by(|a, b| {
|
||||
filled(&b.synced_lyrics)
|
||||
.is_some()
|
||||
.cmp(&filled(&a.synced_lyrics).is_some())
|
||||
.then(off(a).total_cmp(&off(b)))
|
||||
})
|
||||
}
|
||||
|
||||
/// `None` on 404, which LRCLIB answers when it has no such track.
|
||||
async fn get<T: serde::de::DeserializeOwned>(
|
||||
http: &reqwest::Client,
|
||||
endpoint: &str,
|
||||
query: &[(&str, &str)],
|
||||
) -> Result<Option<T>> {
|
||||
let network = |e: reqwest::Error| Error::Network(format!("lrclib: {e}"));
|
||||
let response = http
|
||||
.get(format!("{BASE}/{endpoint}"))
|
||||
.query(query)
|
||||
.header(reqwest::header::USER_AGENT, USER_AGENT)
|
||||
.timeout(TIMEOUT)
|
||||
.send()
|
||||
.await
|
||||
.map_err(network)?;
|
||||
let status = response.status();
|
||||
if status == reqwest::StatusCode::NOT_FOUND {
|
||||
return Ok(None);
|
||||
}
|
||||
if !status.is_success() {
|
||||
return Err(if status.is_server_error() || status == reqwest::StatusCode::TOO_MANY_REQUESTS {
|
||||
Error::Network(format!("lrclib: {status}"))
|
||||
} else {
|
||||
Error::Api(format!("lrclib: {status}"))
|
||||
});
|
||||
}
|
||||
let body = response.bytes().await.map_err(network)?;
|
||||
serde_json::from_slice(&body).map(Some).map_err(|e| Error::Api(format!("lrclib: {e}")))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn records(json: &str) -> Vec<Record> {
|
||||
serde_json::from_str(json).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prefers_synced_then_closest_length() {
|
||||
let found = records(
|
||||
r#"[
|
||||
{"duration":200,"instrumental":false,"plainLyrics":"far","syncedLyrics":"[00:01.00]far"},
|
||||
{"duration":181,"instrumental":false,"plainLyrics":"plain","syncedLyrics":null},
|
||||
{"duration":182,"instrumental":false,"plainLyrics":"x","syncedLyrics":"[00:01.00]near"},
|
||||
{"duration":180,"instrumental":false,"plainLyrics":"y","syncedLyrics":"[00:01.00]exact"}
|
||||
]"#,
|
||||
);
|
||||
let l = pick(found, 180.0).unwrap().into_lyrics().unwrap();
|
||||
assert!(l.synced);
|
||||
assert_eq!(l.lines[0].text, "exact");
|
||||
assert_eq!(l.source, LyricsSource::Lrclib);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skips_instrumentals_and_wrong_lengths() {
|
||||
let found = records(
|
||||
r#"[
|
||||
{"duration":180,"instrumental":true,"plainLyrics":null,"syncedLyrics":null},
|
||||
{"duration":240,"instrumental":false,"plainLyrics":"live","syncedLyrics":null}
|
||||
]"#,
|
||||
);
|
||||
assert!(pick(found, 180.0).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn falls_back_to_plain_text() {
|
||||
let r = records(r#"[{"duration":180,"instrumental":false,"plainLyrics":"a\nb","syncedLyrics":" "}]"#);
|
||||
let l = pick(r, 180.0).unwrap().into_lyrics().unwrap();
|
||||
assert!(!l.synced);
|
||||
assert_eq!(l.lines.len(), 2);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user