Rename module from lyrics-dl
to lrc-dl
This commit is contained in:
parent
4bfcbf17bd
commit
658e1bef77
16 changed files with 52 additions and 52 deletions
3
lrc_dl/providers/__init__.py
Normal file
3
lrc_dl/providers/__init__.py
Normal file
|
@ -0,0 +1,3 @@
|
|||
from lrc_dl.providers import musixmatch
|
||||
from lrc_dl.providers import kugou
|
||||
from lrc_dl.providers import youtube
|
79
lrc_dl/providers/kugou.py
Normal file
79
lrc_dl/providers/kugou.py
Normal file
|
@ -0,0 +1,79 @@
|
|||
from typing import Optional, Iterable
|
||||
from base64 import b64decode
|
||||
import zlib
|
||||
import re
|
||||
from itertools import filterfalse, islice
|
||||
from datetime import datetime
|
||||
|
||||
import httpx
|
||||
|
||||
from lrc_dl.core import Song, AbstractProvider
|
||||
from lrc_dl.registry import lyrics_provider
|
||||
|
||||
|
||||
KRC_ENCODE_KEY = [64, 71, 97, 119, 94, 50, 116, 71, 81, 54, 49, 45, 206, 210, 110, 105]
|
||||
|
||||
RE_KRC_JUNK = re.compile(r"^\[((id|ar|ti|by|hash|al|sign|qq|total|language):|offset:0\]|.*\](<.*>)?(Written by:|Lyrics by:|Composed by:|Producer:|作曲 :|作词 :)).*$")
|
||||
RE_WORD_TIMING = re.compile(r"<-?\d+,-?\d+,-?\d+>")
|
||||
|
||||
|
||||
def decode_krc(content: bytes) -> str:
|
||||
content = b64decode(content)
|
||||
|
||||
buf = bytearray(len(content) - 4)
|
||||
for i in range(4, len(content)):
|
||||
buf[i - 4] = content[i] ^ KRC_ENCODE_KEY[(i - 4) % 16]
|
||||
|
||||
return zlib.decompress(buf).decode('utf-8-sig')
|
||||
|
||||
|
||||
def reformat_timings(lines: Iterable[str]) -> Iterable[str]:
|
||||
for line in lines:
|
||||
if not line.startswith("["):
|
||||
yield line
|
||||
continue
|
||||
|
||||
raw_timings, text = line.split("]", 1)
|
||||
beginning, _ = map(int, raw_timings[1:].split(","))
|
||||
|
||||
timing = datetime.fromtimestamp(beginning / 1000).strftime("%M:%S.%f")[:8]
|
||||
|
||||
yield f"[{timing}]{text}"
|
||||
|
||||
|
||||
@lyrics_provider
|
||||
class Kugou(AbstractProvider):
|
||||
name = "kugou"
|
||||
|
||||
def fetch_lyrics(self: AbstractProvider, song: Song) -> Optional[str]:
|
||||
keyword = f"{song.artist} - {song.title}"
|
||||
|
||||
response = httpx.get("https://krcs.kugou.com/search", params={
|
||||
"ver": 1,
|
||||
"man": "yes",
|
||||
"client": "mobi",
|
||||
"keyword": keyword
|
||||
}).json()
|
||||
|
||||
candidates = response["candidates"]
|
||||
|
||||
if not candidates:
|
||||
return None
|
||||
|
||||
id_, accesskey = candidates[0]["id"], candidates[0]["accesskey"]
|
||||
|
||||
r = httpx.get("https://krcs.kugou.com/download", params={
|
||||
"ver": 1,
|
||||
"man": "yes",
|
||||
"client": "mobi",
|
||||
"format": "lrc",
|
||||
"id": id_,
|
||||
"accesskey": accesskey
|
||||
}).json()
|
||||
|
||||
krc = decode_krc(r["content"])
|
||||
|
||||
krc = RE_WORD_TIMING.sub("", krc)
|
||||
lines = reformat_timings(islice(filterfalse(RE_KRC_JUNK.match, krc.splitlines()), 1, None))
|
||||
|
||||
return "\n".join(lines)
|
36
lrc_dl/providers/musixmatch.py
Normal file
36
lrc_dl/providers/musixmatch.py
Normal file
|
@ -0,0 +1,36 @@
|
|||
from typing import Optional
|
||||
import httpx
|
||||
|
||||
from lrc_dl.core import Song, AbstractProvider
|
||||
from lrc_dl.registry import lyrics_provider
|
||||
|
||||
|
||||
@lyrics_provider
|
||||
class Musixmatch(AbstractProvider):
|
||||
name = "musixmatch"
|
||||
|
||||
def __init__(self, token: str) -> None:
|
||||
self.token = token
|
||||
|
||||
def fetch_lyrics(self, song: Song) -> Optional[str]:
|
||||
response = httpx.get("https://apic-desktop.musixmatch.com/ws/1.1/macro.subtitles.get", params={
|
||||
"format": "json",
|
||||
"namespace": "lyrics_synched",
|
||||
"part": "lyrics_crowd,user,lyrics_verified_by",
|
||||
"user_language": "en",
|
||||
"f_subtitle_length_max_deviation": 1,
|
||||
"subtitle_format": "lrc",
|
||||
"app_id": "web-desktop-app-v1.0",
|
||||
"usertoken": self.token,
|
||||
|
||||
"q_artist": song.artist,
|
||||
"q_track": song.title,
|
||||
"q_album": song.album,
|
||||
}, follow_redirects=True).json()
|
||||
|
||||
response = response["message"]["body"]["macro_calls"]["track.subtitles.get"]["message"]["body"]
|
||||
|
||||
if not response:
|
||||
return None
|
||||
|
||||
return response["subtitle_list"][0]["subtitle"]["subtitle_body"]
|
79
lrc_dl/providers/youtube.py
Normal file
79
lrc_dl/providers/youtube.py
Normal file
|
@ -0,0 +1,79 @@
|
|||
from typing import Optional, Dict
|
||||
from contextlib import redirect_stdout
|
||||
import subprocess
|
||||
import io
|
||||
import urllib
|
||||
import unittest.mock
|
||||
|
||||
from yt_dlp import YoutubeDL
|
||||
|
||||
from lrc_dl.core import Song, AbstractProvider
|
||||
from lrc_dl.registry import lyrics_provider
|
||||
from lrc_dl import utils
|
||||
|
||||
|
||||
@lyrics_provider
|
||||
class Youtube(AbstractProvider):
|
||||
name = "youtube"
|
||||
|
||||
def _craft_search_link(self, song: Song) -> str:
|
||||
query = f"{song.artist} - {song.title}"
|
||||
query = urllib.parse.quote(query)
|
||||
# sp=... means search only videos with subtitles
|
||||
url = f"https://www.youtube.com/results?search_query={query}&sp=EgIoAQ%253D%253D"
|
||||
return url
|
||||
|
||||
def _download_subtitles(self, video_id: str) -> str:
|
||||
# buffer = io.BytesIO()
|
||||
buffer = io.StringIO()
|
||||
|
||||
# A dirty monkey patch; youtube-dl does not
|
||||
# support "-" filename for subtitles, so we
|
||||
# just force it to use it here.
|
||||
with unittest.mock.patch("yt_dlp.YoutubeDL.subtitles_filename", new=lambda *_: "-"):
|
||||
with redirect_stdout(buffer):
|
||||
with YoutubeDL({"writesubtitles": True, "skip_download": True, "subtitlesformat": "srt/vtt/best", 'logtostderr': True}) as ydl:
|
||||
ydl.download(video_id)
|
||||
|
||||
return buffer.getvalue()
|
||||
|
||||
def _subtitles_to_lyrics(self, subtitles: str) -> str:
|
||||
# "-fflags +bitexact" prevents ffmpeg from
|
||||
# writing metadata to .lrc file
|
||||
# TODO: use `with` statement
|
||||
process = subprocess.Popen(["ffmpeg", "-loglevel", "quiet", "-i", "-", "-f", "lrc", "-fflags", "+bitexact", "-"], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
|
||||
|
||||
if not process.stdin or not process.stdout:
|
||||
return ""
|
||||
|
||||
process.stdin.write(subtitles.encode())
|
||||
process.stdin.close()
|
||||
process.wait()
|
||||
return process.stdout.read().decode()[1:]
|
||||
|
||||
def fetch_lyrics(self, song: Song) -> Optional[str]:
|
||||
search_link = self._craft_search_link(song)
|
||||
with YoutubeDL({"extract_flat": True, "playlistend": 10}) as ydl:
|
||||
videos = ydl.extract_info(search_link)["entries"]
|
||||
|
||||
if song.duration:
|
||||
def match_duration(video: Dict) -> bool:
|
||||
return utils.threshold_equal(video["duration"], song.duration, 2)
|
||||
videos = filter(match_duration, videos)
|
||||
|
||||
def match_title(video: Dict) -> bool:
|
||||
return True
|
||||
videos = filter(match_title, videos)
|
||||
|
||||
video = utils.next_or_none(videos)
|
||||
|
||||
if not video:
|
||||
return None
|
||||
|
||||
subtitles = self._download_subtitles(video["id"])
|
||||
lyrics = self._subtitles_to_lyrics(subtitles)
|
||||
|
||||
if lyrics != "":
|
||||
return lyrics
|
||||
|
||||
return None
|
Loading…
Add table
Add a link
Reference in a new issue