feat: サブカル・ボカロ特化の歌詞取得(Kugou/VocaDB)連携およびYouTube字幕取得の制限機能の実装
This commit is contained in:
1 parent
07315c475b
commit
d12bd07664
5 files changed
+369
-21
No files matched your search
@@ -503,7 +503,9 @@ namespace MusicDownloader.Class.Downloader
|
||||
}
|
||||
|
||||
// 歌詞処理 (.lrc作成および歌詞テキスト取得) - stagingDir 内に生成
|
||||
var lyrics = await _lyricsManager.ProcessLyricsAsync(targetOpus, finalTitle, finalArtist, entryInfo?.Duration, stagingDir, null);
|
||||
// 【要件】YouTube字幕の利用はYouTube Music公式曲(アーティスト・アルバム等の取得可能曲)に限定
|
||||
bool isOfficialMusic = hasYoutubeTrack || hasYoutubeArtist || hasYoutubeAlbum;
|
||||
var lyrics = await _lyricsManager.ProcessLyricsAsync(targetOpus, finalTitle, finalArtist, entryInfo?.Duration, stagingDir, isOfficialMusic: isOfficialMusic, filePrefix: null);
|
||||
|
||||
// メタデータ (TagLibSharp) の書き込み(正確な曲名・アーティスト・アルバム・アルバムアーティスト)
|
||||
AudioTagManager.ApplyMetadata(
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Net.Http;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MusicDownloader.Class.Lyrics
|
||||
{
|
||||
public class KugouSearchResponse
|
||||
{
|
||||
[JsonPropertyName("data")]
|
||||
public KugouSearchData? Data { get; set; }
|
||||
}
|
||||
|
||||
public class KugouSearchData
|
||||
{
|
||||
[JsonPropertyName("info")]
|
||||
public List<KugouSongInfo>? Info { get; set; }
|
||||
}
|
||||
|
||||
public class KugouSongInfo
|
||||
{
|
||||
[JsonPropertyName("songname")]
|
||||
public string? SongName { get; set; }
|
||||
|
||||
[JsonPropertyName("singername")]
|
||||
public string? SingerName { get; set; }
|
||||
|
||||
[JsonPropertyName("hash")]
|
||||
public string? Hash { get; set; }
|
||||
|
||||
[JsonPropertyName("duration")]
|
||||
public int? Duration { get; set; }
|
||||
}
|
||||
|
||||
public class KugouCandidateResponse
|
||||
{
|
||||
[JsonPropertyName("candidates")]
|
||||
public List<KugouCandidate>? Candidates { get; set; }
|
||||
}
|
||||
|
||||
public class KugouCandidate
|
||||
{
|
||||
[JsonPropertyName("id")]
|
||||
public string? Id { get; set; }
|
||||
|
||||
[JsonPropertyName("accesskey")]
|
||||
public string? AccessKey { get; set; }
|
||||
|
||||
[JsonPropertyName("song")]
|
||||
public string? Song { get; set; }
|
||||
|
||||
[JsonPropertyName("singer")]
|
||||
public string? Singer { get; set; }
|
||||
}
|
||||
|
||||
public class KugouDownloadResponse
|
||||
{
|
||||
[JsonPropertyName("status")]
|
||||
public int Status { get; set; }
|
||||
|
||||
[JsonPropertyName("content")]
|
||||
public string? Content { get; set; }
|
||||
|
||||
[JsonPropertyName("fmt")]
|
||||
public string? Fmt { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// サブカル・ボカロ・アニソン・同人曲の同期歌詞(LRC)を豊富に保持する Kugou API クライアント
|
||||
/// </summary>
|
||||
public class KugouLyricsClient
|
||||
{
|
||||
private readonly HttpClient _httpClient;
|
||||
|
||||
public KugouLyricsClient(HttpClient httpClient)
|
||||
{
|
||||
_httpClient = httpClient;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 曲名とアーティスト名から高精度な同期歌詞(.lrc)を取得する
|
||||
/// </summary>
|
||||
public async Task<string?> GetLyricsAsync(string title, string artist, double? durationSeconds)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(title)) return null;
|
||||
|
||||
try
|
||||
{
|
||||
var query = !string.IsNullOrWhiteSpace(artist) && artist != "Unknown"
|
||||
? $"{title} {artist}"
|
||||
: title;
|
||||
|
||||
// 1. 楽曲検索
|
||||
var searchUrl = $"http://mobilecdn.kugou.com/api/v3/search/song?format=json&keyword={Uri.EscapeDataString(query)}&page=1&pagesize=5";
|
||||
using var searchReq = new HttpRequestMessage(HttpMethod.Get, searchUrl);
|
||||
searchReq.Headers.UserAgent.ParseAdd(CmnDefine.UserAgent);
|
||||
|
||||
var searchRes = await _httpClient.SendAsync(searchReq);
|
||||
if (!searchRes.IsSuccessStatusCode) return null;
|
||||
|
||||
var searchJson = await searchRes.Content.ReadAsStringAsync();
|
||||
var searchResult = JsonSerializer.Deserialize<KugouSearchResponse>(searchJson);
|
||||
var songList = searchResult?.Data?.Info;
|
||||
if (songList == null || songList.Count == 0) return null;
|
||||
|
||||
// 曲名の一致判定を行い、最も一致する候補を選択
|
||||
KugouSongInfo? matchedSong = null;
|
||||
foreach (var s in songList)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(s.Hash)) continue;
|
||||
if (CmnUtil.IsConfidentTitleMatch(title, s.SongName))
|
||||
{
|
||||
matchedSong = s;
|
||||
break;
|
||||
}
|
||||
}
|
||||
matchedSong ??= songList[0];
|
||||
|
||||
if (string.IsNullOrWhiteSpace(matchedSong.Hash)) return null;
|
||||
|
||||
// 2. 歌詞候補の検索
|
||||
var krcUrl = $"http://krcs.kugou.com/search?ver=1&man=yes&client=mobi&keyword={Uri.EscapeDataString(matchedSong.SongName ?? title)}&hash={matchedSong.Hash}";
|
||||
using var krcReq = new HttpRequestMessage(HttpMethod.Get, krcUrl);
|
||||
krcReq.Headers.UserAgent.ParseAdd(CmnDefine.UserAgent);
|
||||
|
||||
var krcRes = await _httpClient.SendAsync(krcReq);
|
||||
if (!krcRes.IsSuccessStatusCode) return null;
|
||||
|
||||
var krcJson = await krcRes.Content.ReadAsStringAsync();
|
||||
var krcResult = JsonSerializer.Deserialize<KugouCandidateResponse>(krcJson);
|
||||
var candidates = krcResult?.Candidates;
|
||||
if (candidates == null || candidates.Count == 0) return null;
|
||||
|
||||
var targetCandidate = candidates[0];
|
||||
if (string.IsNullOrWhiteSpace(targetCandidate.Id) || string.IsNullOrWhiteSpace(targetCandidate.AccessKey))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
// 3. LRC歌詞データのダウンロード (UTF-8)
|
||||
var downloadUrl = $"http://lyrics.kugou.com/download?ver=1&client=pc&id={targetCandidate.Id}&accesskey={targetCandidate.AccessKey}&fmt=lrc&charset=utf8";
|
||||
using var dlReq = new HttpRequestMessage(HttpMethod.Get, downloadUrl);
|
||||
dlReq.Headers.UserAgent.ParseAdd(CmnDefine.UserAgent);
|
||||
|
||||
var dlRes = await _httpClient.SendAsync(dlReq);
|
||||
if (!dlRes.IsSuccessStatusCode) return null;
|
||||
|
||||
var dlJson = await dlRes.Content.ReadAsStringAsync();
|
||||
var dlResult = JsonSerializer.Deserialize<KugouDownloadResponse>(dlJson);
|
||||
if (dlResult == null || string.IsNullOrWhiteSpace(dlResult.Content)) return null;
|
||||
|
||||
// Base64デコード
|
||||
var lrcBytes = Convert.FromBase64String(dlResult.Content);
|
||||
var lrcText = Encoding.UTF8.GetString(lrcBytes);
|
||||
|
||||
// LRCヘッダまたはタイムスタンプが含まれているか確認
|
||||
if (lrcText.Contains("[00:") || lrcText.Contains("[01:") || lrcText.Contains("[02:"))
|
||||
{
|
||||
return lrcText;
|
||||
}
|
||||
|
||||
return !string.IsNullOrWhiteSpace(lrcText) ? lrcText : null;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogManager.AddWarning($"Kugou歌詞検索中にエラー: {ex.Message}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,10 +11,17 @@ namespace MusicDownloader.Class.Lyrics
|
||||
public class LyricsManager
|
||||
{
|
||||
private readonly LrcLibClient _lrcLibClient;
|
||||
private readonly KugouLyricsClient _kugouClient;
|
||||
private readonly VocaDbLyricsClient _vocaDbClient;
|
||||
|
||||
public LyricsManager(LrcLibClient lrcLibClient)
|
||||
public LyricsManager(
|
||||
LrcLibClient lrcLibClient,
|
||||
KugouLyricsClient kugouClient,
|
||||
VocaDbLyricsClient vocaDbClient)
|
||||
{
|
||||
_lrcLibClient = lrcLibClient;
|
||||
_kugouClient = kugouClient;
|
||||
_vocaDbClient = vocaDbClient;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -25,43 +32,74 @@ namespace MusicDownloader.Class.Lyrics
|
||||
/// <param name="artist">アーティスト名</param>
|
||||
/// <param name="duration">再生時間(秒)</param>
|
||||
/// <param name="workDir">一時ファイル・字幕ファイルが存在する作業ディレクトリ</param>
|
||||
/// <param name="isOfficialMusic">YouTube Music等でアーティストやアルバム等が取得できる公式曲かどうか</param>
|
||||
/// <param name="filePrefix">該当曲のファイルプレフィックス(例: "01 - ")</param>
|
||||
/// <returns>取得・生成できた歌詞文字列(タグ埋め込み用)</returns>
|
||||
public async Task<string?> ProcessLyricsAsync(string opusFilePath, string title, string artist, double? duration, string workDir, string? filePrefix = null)
|
||||
public async Task<string?> ProcessLyricsAsync(
|
||||
string opusFilePath,
|
||||
string title,
|
||||
string artist,
|
||||
double? duration,
|
||||
string workDir,
|
||||
bool isOfficialMusic,
|
||||
string? filePrefix = null)
|
||||
{
|
||||
var lrcPath = Path.ChangeExtension(opusFilePath, ".lrc");
|
||||
|
||||
// 1. LRCLIB APIからの同期歌詞取得を試行
|
||||
LogManager.AddLog($"歌詞の検索を開始: 「{artist} - {title}」");
|
||||
|
||||
// 1. LRCLIB APIからの同期歌詞取得を試行
|
||||
try
|
||||
{
|
||||
var lrcResponse = await _lrcLibClient.GetLyricsAsync(title, artist, duration);
|
||||
if (lrcResponse != null)
|
||||
{
|
||||
// 同期歌詞 (Synced Lyrics) が存在する場合
|
||||
if (!string.IsNullOrWhiteSpace(lrcResponse.SyncedLyrics))
|
||||
if (lrcResponse != null && !string.IsNullOrWhiteSpace(lrcResponse.SyncedLyrics))
|
||||
{
|
||||
await File.WriteAllTextAsync(lrcPath, lrcResponse.SyncedLyrics, Encoding.UTF8);
|
||||
LogManager.AddSuccess($"LRCLIBより同期歌詞(.lrc)を取得・保存しました: {Path.GetFileName(lrcPath)}");
|
||||
return lrcResponse.SyncedLyrics;
|
||||
}
|
||||
// プレーン歌詞が存在する場合
|
||||
if (!string.IsNullOrWhiteSpace(lrcResponse.PlainLyrics))
|
||||
{
|
||||
LogManager.AddLog($"同期歌詞は見つかりませんでしたが、テキスト歌詞を取得しました。");
|
||||
// タグ埋め込み用としてプレーン歌詞を保持
|
||||
// なおPowerampでの表示補助のためタイムスタンプなしLRCとしても出力可能
|
||||
await File.WriteAllTextAsync(lrcPath, lrcResponse.PlainLyrics, Encoding.UTF8);
|
||||
return lrcResponse.PlainLyrics;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogManager.AddWarning($"LRCLIB検索中にエラーが発生しました: {ex.Message}");
|
||||
}
|
||||
|
||||
// 2. フォールバック: YouTubeからダウンロードされた字幕 (.vtt) を探してLRCに変換
|
||||
// 2. 【要件】サブカル・ボカロ・アニソンに強い Kugou データベースからの同期歌詞取得を試行
|
||||
try
|
||||
{
|
||||
var kugouLrc = await _kugouClient.GetLyricsAsync(title, artist, duration);
|
||||
if (!string.IsNullOrWhiteSpace(kugouLrc))
|
||||
{
|
||||
await File.WriteAllTextAsync(lrcPath, kugouLrc, Encoding.UTF8);
|
||||
LogManager.AddSuccess($"Kugou音楽データベースより同期歌詞(.lrc)を取得・保存しました: {Path.GetFileName(lrcPath)}");
|
||||
return kugouLrc;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogManager.AddWarning($"Kugou歌詞検索中にエラーが発生しました: {ex.Message}");
|
||||
}
|
||||
|
||||
// 3. 【要件】ボカロ曲・サブカル特化 VocaDB からの公式歌詞テキスト取得を試行
|
||||
try
|
||||
{
|
||||
var vocaDbLyric = await _vocaDbClient.GetLyricsAsync(title, artist);
|
||||
if (!string.IsNullOrWhiteSpace(vocaDbLyric))
|
||||
{
|
||||
await File.WriteAllTextAsync(lrcPath, vocaDbLyric, Encoding.UTF8);
|
||||
LogManager.AddSuccess($"VocaDBデータベースより公式歌詞を取得・保存しました: {Path.GetFileName(lrcPath)}");
|
||||
return vocaDbLyric;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogManager.AddWarning($"VocaDB歌詞検索中にエラーが発生しました: {ex.Message}");
|
||||
}
|
||||
|
||||
// 4. 【要件】YouTube字幕 (.vtt) からのLRC変換
|
||||
// ※ YouTubeの字幕は壊れているものが多いため、YouTube Music公式情報(アーティスト・アルバム等)がある曲に限定して適用
|
||||
if (isOfficialMusic)
|
||||
{
|
||||
try
|
||||
{
|
||||
var searchPattern = !string.IsNullOrEmpty(filePrefix) ? $"{filePrefix}*.vtt" : "*.vtt";
|
||||
@@ -80,14 +118,14 @@ namespace MusicDownloader.Class.Lyrics
|
||||
}
|
||||
targetVtt ??= vttFiles[0];
|
||||
|
||||
LogManager.AddLog($"YouTube字幕ファイル({Path.GetFileName(targetVtt)})からLRCへの変換を試行します...");
|
||||
LogManager.AddLog($"[YouTube公式曲フォールバック] YouTube字幕ファイル({Path.GetFileName(targetVtt)})からLRCへの変換を試行します...");
|
||||
var vttContent = await File.ReadAllTextAsync(targetVtt, Encoding.UTF8);
|
||||
var convertedLrc = VttToLrcConverter.ConvertVttToLrc(vttContent);
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(convertedLrc))
|
||||
{
|
||||
await File.WriteAllTextAsync(lrcPath, convertedLrc, Encoding.UTF8);
|
||||
LogManager.AddSuccess($"YouTube字幕より同期歌詞(.lrc)を生成・保存しました: {Path.GetFileName(lrcPath)}");
|
||||
LogManager.AddSuccess($"YouTube公式字幕より同期歌詞(.lrc)を生成・保存しました: {Path.GetFileName(lrcPath)}");
|
||||
return convertedLrc;
|
||||
}
|
||||
}
|
||||
@@ -96,6 +134,11 @@ namespace MusicDownloader.Class.Lyrics
|
||||
{
|
||||
LogManager.AddWarning($"字幕ファイルからのLRC変換中にエラーが発生しました: {ex.Message}");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
LogManager.AddLog($"[YouTube字幕スキップ] YouTube Music公式曲ではないため、YouTube字幕からの歌詞変換は行いません。");
|
||||
}
|
||||
|
||||
LogManager.AddLog($"歌詞情報は取得できませんでした。");
|
||||
return null;
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MusicDownloader.Class.Lyrics
|
||||
{
|
||||
public class VocaDbSongResponse
|
||||
{
|
||||
[JsonPropertyName("items")]
|
||||
public List<VocaDbSongItem>? Items { get; set; }
|
||||
}
|
||||
|
||||
public class VocaDbSongItem
|
||||
{
|
||||
[JsonPropertyName("id")]
|
||||
public int Id { get; set; }
|
||||
|
||||
[JsonPropertyName("name")]
|
||||
public string? Name { get; set; }
|
||||
|
||||
[JsonPropertyName("artistString")]
|
||||
public string? ArtistString { get; set; }
|
||||
|
||||
[JsonPropertyName("lyrics")]
|
||||
public List<VocaDbLyricItem>? Lyrics { get; set; }
|
||||
}
|
||||
|
||||
public class VocaDbLyricItem
|
||||
{
|
||||
[JsonPropertyName("cultureCode")]
|
||||
public string? CultureCode { get; set; }
|
||||
|
||||
[JsonPropertyName("translationType")]
|
||||
public string? TranslationType { get; set; }
|
||||
|
||||
[JsonPropertyName("value")]
|
||||
public string? Value { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// VOCALOID / UTAU / CeVIO 等のサブカル・ボカロ楽曲データベース VocaDB 歌詞クライアント
|
||||
/// </summary>
|
||||
public class VocaDbLyricsClient
|
||||
{
|
||||
private readonly HttpClient _httpClient;
|
||||
|
||||
public VocaDbLyricsClient(HttpClient httpClient)
|
||||
{
|
||||
_httpClient = httpClient;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ボカロ曲の公式歌詞テキスト(Original)を検索・取得する
|
||||
/// </summary>
|
||||
public async Task<string?> GetLyricsAsync(string title, string artist)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(title)) return null;
|
||||
|
||||
try
|
||||
{
|
||||
// ボカロ曲オリジナルを優先検索
|
||||
var cleanTitle = CmnUtil.ExtractCoreTitle(title);
|
||||
var url = $"https://vocadb.net/api/songs?query={Uri.EscapeDataString(cleanTitle)}&songTypes=Original&fields=Lyrics,Artists&maxResults=5";
|
||||
|
||||
using var req = new HttpRequestMessage(HttpMethod.Get, url);
|
||||
req.Headers.UserAgent.ParseAdd(CmnDefine.UserAgent);
|
||||
|
||||
var res = await _httpClient.SendAsync(req);
|
||||
if (!res.IsSuccessStatusCode) return null;
|
||||
|
||||
var json = await res.Content.ReadAsStringAsync();
|
||||
var data = JsonSerializer.Deserialize<VocaDbSongResponse>(json);
|
||||
if (data?.Items == null || data.Items.Count == 0) return null;
|
||||
|
||||
// 曲名の一致判定
|
||||
foreach (var item in data.Items)
|
||||
{
|
||||
if (item.Lyrics == null || item.Lyrics.Count == 0) continue;
|
||||
|
||||
if (CmnUtil.IsConfidentTitleMatch(title, item.Name))
|
||||
{
|
||||
// 原語(Original)または日本語の歌詞を優先
|
||||
VocaDbLyricItem? chosen = null;
|
||||
foreach (var l in item.Lyrics)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(l.Value)) continue;
|
||||
if (string.Equals(l.TranslationType, "Original", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
chosen = l;
|
||||
break;
|
||||
}
|
||||
if (string.Equals(l.CultureCode, "ja", StringComparison.OrdinalIgnoreCase) ||
|
||||
string.Equals(l.CultureCode, "ja-JP", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
chosen ??= l;
|
||||
}
|
||||
}
|
||||
chosen ??= item.Lyrics[0];
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(chosen.Value))
|
||||
{
|
||||
return chosen.Value.Trim();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogManager.AddWarning($"VocaDB歌詞検索中にエラー: {ex.Message}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -65,6 +65,16 @@ services.AddSingleton<LrcLibClient>(sp =>
|
||||
var factory = sp.GetRequiredService<IHttpClientFactory>();
|
||||
return new LrcLibClient(factory.CreateClient("webClient"));
|
||||
});
|
||||
services.AddSingleton<KugouLyricsClient>(sp =>
|
||||
{
|
||||
var factory = sp.GetRequiredService<IHttpClientFactory>();
|
||||
return new KugouLyricsClient(factory.CreateClient("webClient"));
|
||||
});
|
||||
services.AddSingleton<VocaDbLyricsClient>(sp =>
|
||||
{
|
||||
var factory = sp.GetRequiredService<IHttpClientFactory>();
|
||||
return new VocaDbLyricsClient(factory.CreateClient("webClient"));
|
||||
});
|
||||
services.AddSingleton<MusicMetadataClient>(sp =>
|
||||
{
|
||||
var factory = sp.GetRequiredService<IHttpClientFactory>();
|
||||
|
||||
Reference in new issue
Block a user