musicpom/utils/get_album_art.py
2026-06-24 14:31:21 -04:00

101 lines
3.1 KiB
Python

from mutagen.id3 import ID3, APIC
from mutagen.flac import FLAC, Picture
from mutagen.mp4 import MP4
from mutagen.wave import WAVE
from mutagen.aiff import AIFF
from logging import debug, error
# def get_album_art(file: str | None) -> bytes:
# """
# Get the album art for an audio file
# # Parameters
# `file` | str | Fully qualified path to file
# # Returns
# bytes for album art or placeholder artwork
# """
# default_image_path = "./assets/default_album_art.jpg"
# if file:
# try:
# audio = ID3(file)
# for tag in audio.getall("APIC"):
# if tag.type == 3: # 3 is the type for front cover
# return tag.data
# if audio.getall("APIC"):
# return audio.getall("APIC")[0].data
# except Exception as e:
# error(f"Error retrieving album art: {e}")
# return bytes()
# with open(default_image_path, "rb") as f:
# # debug("loading placeholder album art")
# return f.read()
def get_album_art(file: str | None) -> bytes:
"""
Get album art for MP3, FLAC, WAV, AIFF, M4A files.
Parameters:
- `file` | str | Fully qualified path to file
Returns:
- bytes for album art or placeholder artwork
"""
default_image_path = "./assets/default_album_art.jpg"
def fallback():
try:
with open(default_image_path, "rb") as f:
return f.read()
except Exception:
return b""
if not file:
return fallback()
try:
ext = file.lower().split(".")[-1]
# ---------------- MP3 ----------------
if ext == "mp3":
audio = ID3(file)
apics = audio.getall("APIC")
if apics:
# prefer front cover (type 3)
for tag in apics:
if tag.type == 3:
return tag.data
return apics[0].data
# ---------------- FLAC ----------------
elif ext == "flac":
audio = FLAC(file)
if audio.pictures:
# prefer front cover
for pic in audio.pictures:
if pic.type == 3:
return pic.data
return audio.pictures[0].data
# ---------------- M4A / MP4 ----------------
elif ext in ("m4a", "mp4"):
audio = MP4(file)
cov = audio.tags.get("covr")
if cov:
# covr is a list of MP4Cover objects
return bytes(cov[0])
# ---------------- WAV ----------------
elif ext == "wav":
return fallback()
# audio = WAVE(file)
# if hasattr(audio, "pictures") and audio.pictures:
# return audio.pictures[0].data
# ---------------- AIFF ----------------
elif ext in ("aiff", "aif"):
return fallback()
# audio = AIFF(file)
# if hasattr(audio, "pictures") and audio.pictures:
# return audio.pictures[0].data
except Exception as e:
error(f"Error retrieving album art: {e}")
return fallback()