Files
lyricsget/lyricsget.py
2026-11-12 13:56:30 +02:00

94 lines
3.0 KiB
Python

import json
import os
import pathlib
from dataclasses import dataclass
import mutagen
import requests
from mutagen.flac import Picture
from mutagen.id3._frames import APIC
@dataclass
class Cover:
data: bytes
mimeType: str
print("Input directory with music")
dir = input()
# TODO: Rename folder like albumYear - albumName
# TODO: Rename song with format like 05 - Song when it 05. Song
for root, _, files in os.walk(dir, topdown=True):
coverData = None
# TODO: Fetch cover from url
for cover in files:
suffix = pathlib.Path(cover).suffix
if suffix == ".jpg":
path = root + "/" + cover
data = None
with open(path, "rb") as f:
data = f.read()
coverData = Cover(data=data, mimeType="image/jpeg")
break
elif suffix == ".png":
path = root + "/" + cover
data = None
with open(path, "rb") as f:
data = f.read()
coverData = Cover(data=data, mimeType="image/png")
break
for file in files:
suffix = pathlib.Path(file).suffix
if suffix == ".flac" or suffix == ".mp3":
try:
path = root + "/" + file
audio = mutagen.File(path)
params = {
"artist_name": audio["artist"],
"track_name": audio["title"],
"album_name": audio["album"],
"duration": audio.info.length,
}
# Maybe add more sites with lyrics?
lrcreq = requests.get("https://lrclib.net/api/get", params)
if lrcreq.status_code == 200:
jsonLyrics = json.loads(lrcreq.text)
if "syncedLyrics" in jsonLyrics:
audio["lyrics"] = jsonLyrics["syncedLyrics"]
else:
audio["lyrics"] = jsonLyrics["plainLyrics"]
else:
print(lrcreq.text)
if coverData is not None:
if suffix == ".flac":
pic = Picture()
pic.type = 3
pic.mime = coverData.mimeType
pic.data = coverData.data
audio.add_picture(pic)
elif suffix == ".mp3":
if not audio.tags:
audio.add_tags()
audio.tags.add(
APIC(
encoding=3,
mime=coverData.mimeType,
type=3,
data=coverData.data,
)
)
audio.save()
except Exception as e:
print(f"Error while trying to clean the music: {e}")