Files
jellyfin-plugin-yandexmusic/Jellyfin.Plugin.YandexMusic/Matching/TextMatch.cs
T

298 lines
8.8 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
using Jellyfin.Plugin.YandexMusic.Yandex;
namespace Jellyfin.Plugin.YandexMusic.Matching;
/// <summary>
/// Text normalization and fuzzy matching helpers.
/// </summary>
public static partial class TextMatch
{
/// <summary>Normalizes a title or artist name for comparison.</summary>
public static string Normalize(string? value)
{
if (string.IsNullOrWhiteSpace(value))
{
return string.Empty;
}
var text = value.ToLowerInvariant().Replace('ё', 'е');
text = ParenthesesRegex().Replace(text, " ");
text = BracketsRegex().Replace(text, " ");
var featIndex = text.IndexOf(" feat", StringComparison.Ordinal);
if (featIndex > 0)
{
text = text[..featIndex];
}
var builder = new StringBuilder(text.Length);
var previousSpace = true;
foreach (var ch in text)
{
if (char.IsLetterOrDigit(ch))
{
builder.Append(ch);
previousSpace = false;
}
else if (!previousSpace)
{
builder.Append(' ');
previousSpace = true;
}
}
return builder.ToString().Trim();
}
/// <summary>Similarity in range 0..1 (best of edit distance ratio and token overlap).</summary>
public static double Similarity(string? left, string? right)
{
var a = Normalize(left);
var b = Normalize(right);
if (a.Length == 0 || b.Length == 0)
{
return 0;
}
if (string.Equals(a, b, StringComparison.Ordinal))
{
return 1;
}
return Math.Max(LevenshteinRatio(a, b), TokenJaccard(a, b));
}
/// <summary>Best similarity between two artist lists.</summary>
public static double ArtistSimilarity(IEnumerable<string?> left, IEnumerable<string?> right)
{
var leftParts = left.SelectMany(SplitArtists).ToArray();
var rightParts = right.SelectMany(SplitArtists).ToArray();
var best = 0d;
foreach (var a in leftParts)
{
foreach (var b in rightParts)
{
best = Math.Max(best, Similarity(a, b));
}
}
return best;
}
/// <summary>Splits a combined artist string ("A, B &amp; C feat. D") into individual names.</summary>
public static IEnumerable<string> SplitArtists(string? value)
{
if (string.IsNullOrWhiteSpace(value))
{
yield break;
}
var text = value.Replace(" & ", ", ", StringComparison.Ordinal)
.Replace(" and ", ", ", StringComparison.OrdinalIgnoreCase)
.Replace(" feat. ", ", ", StringComparison.OrdinalIgnoreCase)
.Replace(" feat ", ", ", StringComparison.OrdinalIgnoreCase);
foreach (var part in text.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
{
if (part.Length > 0)
{
yield return part;
}
}
}
private static double LevenshteinRatio(string a, string b)
{
var distance = Levenshtein(a, b);
var max = Math.Max(a.Length, b.Length);
return max == 0 ? 1 : 1d - (double)distance / max;
}
private static int Levenshtein(string a, string b)
{
if (a.Length == 0)
{
return b.Length;
}
if (b.Length == 0)
{
return a.Length;
}
var previous = new int[b.Length + 1];
var current = new int[b.Length + 1];
for (var j = 0; j <= b.Length; j++)
{
previous[j] = j;
}
for (var i = 1; i <= a.Length; i++)
{
current[0] = i;
for (var j = 1; j <= b.Length; j++)
{
var cost = a[i - 1] == b[j - 1] ? 0 : 1;
current[j] = Math.Min(
Math.Min(current[j - 1] + 1, previous[j] + 1),
previous[j - 1] + cost);
}
(previous, current) = (current, previous);
}
return previous[b.Length];
}
private static double TokenJaccard(string a, string b)
{
var left = a.Split(' ', StringSplitOptions.RemoveEmptyEntries);
var right = b.Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (left.Length == 0 || right.Length == 0)
{
return 0;
}
var common = left.Intersect(right, StringComparer.Ordinal).Count();
var union = left.Union(right, StringComparer.Ordinal).Count();
return union == 0 ? 0 : (double)common / union;
}
[GeneratedRegex(@"\([^)]*\)", RegexOptions.CultureInvariant)]
private static partial Regex ParenthesesRegex();
[GeneratedRegex(@"\[[^\]]*\]", RegexOptions.CultureInvariant)]
private static partial Regex BracketsRegex();
}
/// <summary>
/// Scores Yandex search results against local tags.
/// </summary>
public static class MatchScoring
{
/// <summary>Duration in milliseconds from Jellyfin ticks.</summary>
public static long TicksToMilliseconds(long? ticks)
=> ticks is null ? 0 : ticks.Value / TimeSpan.TicksPerMillisecond;
/// <summary>Finds the best matching track.</summary>
public static (TrackDto Track, double Score)? FindBestTrack(
IEnumerable<TrackDto> tracks,
string? title,
IReadOnlyList<string> artists,
long durationMs,
double threshold,
int toleranceSeconds)
{
(TrackDto Track, double Score)? best = null;
foreach (var track in tracks)
{
var titleScore = TextMatch.Similarity(title, track.Title);
var artistScore = TextMatch.ArtistSimilarity(
artists,
track.Artists.Select(a => a.Name));
var durationScore = DurationScore(durationMs, track.DurationMs, toleranceSeconds);
var score = durationScore is null
? (0.6 * titleScore) + (0.4 * artistScore)
: (0.5 * titleScore) + (0.3 * artistScore) + (0.2 * durationScore.Value);
if (titleScore < 0.68 || artistScore < 0.42)
{
continue;
}
if (best is null || score > best.Value.Score)
{
best = (track, score);
}
}
return best is not null && best.Value.Score >= threshold ? best : null;
}
/// <summary>Finds the best matching album.</summary>
public static (AlbumDto Album, double Score)? FindBestAlbum(
IEnumerable<AlbumDto> albums,
string? title,
IReadOnlyList<string> artists,
int? year,
double threshold)
{
(AlbumDto Album, double Score)? best = null;
foreach (var album in albums)
{
var titleScore = TextMatch.Similarity(title, album.Title);
var artistScore = artists.Count == 0
? 1
: TextMatch.ArtistSimilarity(artists, album.Artists.Select(a => a.Name));
var yearScore = year is null || album.Year is null ? 0.5 : (year == album.Year ? 1 : 0);
var score = (0.55 * titleScore) + (0.3 * artistScore) + (0.15 * yearScore);
if (titleScore < 0.6)
{
continue;
}
if (best is null || score > best.Value.Score)
{
best = (album, score);
}
}
return best is not null && best.Value.Score >= threshold ? best : null;
}
/// <summary>Finds an artist whose name matches exactly (or nearly exactly).</summary>
public static ArtistDto? FindBestArtist(IEnumerable<ArtistDto> artists, string? name)
{
var normalized = TextMatch.Normalize(name);
if (normalized.Length == 0)
{
return null;
}
ArtistDto? best = null;
var bestScore = 0d;
foreach (var artist in artists)
{
var score = TextMatch.Similarity(normalized, artist.Name);
if (score > bestScore)
{
bestScore = score;
best = artist;
}
}
return bestScore >= 0.86 ? best : null;
}
private static double? DurationScore(long localMs, long? remoteMs, int toleranceSeconds)
{
if (localMs <= 0 || remoteMs is null or <= 0)
{
return null;
}
var tolerance = Math.Max(2, toleranceSeconds) * 1000;
var difference = Math.Abs(localMs - remoteMs.Value);
if (difference <= tolerance / 2.0)
{
return 1;
}
if (difference <= tolerance)
{
return 0.85;
}
if (difference <= tolerance * 2.0)
{
return 0.45;
}
return 0.0;
}
}