musicpom/utils/set_tag.py

55 lines
1.9 KiB
Python

from logging import debug, error, warning
from components import ErrorDialog
from components.HeaderTags import HeaderTags2
from mutagen.id3 import ID3
from mutagen.id3._util import ID3NoHeaderError
from mutagen.id3._frames import USLT, Frame
def set_tag(filepath: str, tag_name: str, value: str):
"""
Sets the ID3 tag for a file given a filepath, tag_name, and a value for the tag
Args:
filepath: path to the mp3 file
tag_name: db column name of the ID3 tag
value: value to set for the tag
Returns:
True / False
"""
headers = HeaderTags2()
debug(f"filepath: {filepath} | tag_name: {tag_name} | value: {value}")
try:
try: # Load existing tags
audio_file = ID3(filepath)
except ID3NoHeaderError: # Create new tags if none exist
audio_file = ID3()
# Lyrics get handled differently
if tag_name == "lyrics":
try:
audio = ID3(filepath)
except Exception as e:
error(f"ran into an exception: {e}")
audio = ID3()
audio.delall("USLT")
frame = USLT(encoding=3, text=value)
audio.add(frame)
audio.save()
return True
# DB Tag into Mutagen Frame Class
if tag_name in headers.db:
frame_class = headers.db[tag_name].frame_class
assert frame_class is not None # ooo scary
if issubclass(frame_class, Frame):
frame = frame_class(encoding=3, text=[value])
audio_file.add(frame)
else:
warning(f'Tag "{tag_name}" not found - ID3 tag update skipped')
audio_file.save(filepath)
return True
except Exception as e:
dialog = ErrorDialog(f"set_tag.py | An unhandled exception occurred:\n{e}")
dialog.exec_()
return False