using System.Globalization; using System.Text; using System.Text.RegularExpressions; using Jellyfin.Plugin.YandexMusic.Yandex; namespace Jellyfin.Plugin.YandexMusic.Matching; /// /// Text normalization and fuzzy matching helpers. /// public static partial class TextMatch { /// Normalizes a title or artist name for comparison. 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(); } /// Similarity in range 0..1 (best of edit distance ratio and token overlap). 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)); } /// Best similarity between two artist lists. public static double ArtistSimilarity(IEnumerable left, IEnumerable 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; } /// Splits a combined artist string ("A, B & C feat. D") into individual names. public static IEnumerable 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(); } /// /// Scores Yandex search results against local tags. /// public static class MatchScoring { /// Duration in milliseconds from Jellyfin ticks. public static long TicksToMilliseconds(long? ticks) => ticks is null ? 0 : ticks.Value / TimeSpan.TicksPerMillisecond; /// Finds the best matching track. public static (TrackDto Track, double Score)? FindBestTrack( IEnumerable tracks, string? title, IReadOnlyList artists, long durationMs, double threshold, int toleranceSeconds) { (TrackDto Track, double Score)? best = null; var hasArtists = artists.Any(a => !string.IsNullOrWhiteSpace(a)); foreach (var track in tracks) { var titleScore = TextMatch.Similarity(title, track.Title); var artistScore = hasArtists ? TextMatch.ArtistSimilarity(artists, track.Artists.Select(a => a.Name)) : 1; var durationScore = DurationScore(durationMs, track.DurationMs, toleranceSeconds); double score; if (hasArtists) { if (titleScore < 0.68 || artistScore < 0.42) { continue; } score = durationScore is null ? (0.6 * titleScore) + (0.4 * artistScore) : (0.5 * titleScore) + (0.3 * artistScore) + (0.2 * durationScore.Value); } else { // No artist tags at all: rely on the title and, when available, the duration. if (titleScore < 0.8) { continue; } score = durationScore is null ? titleScore : (0.65 * titleScore) + (0.35 * durationScore.Value); } if (best is null || score > best.Value.Score) { best = (track, score); } } return best is not null && best.Value.Score >= threshold ? best : null; } /// Finds the best matching album. public static (AlbumDto Album, double Score)? FindBestAlbum( IEnumerable albums, string? title, IReadOnlyList 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; } /// Finds an artist whose name matches exactly (or nearly exactly). public static ArtistDto? FindBestArtist(IEnumerable 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; } }