Rewrite tag handling

This commit is contained in:
gryf committed 2026-11-29 17:16:53 +01:00
1 parent e41ba097ef
commit bcacc0df18
2 files changed
+154 -56

No files matched your search

+3 -3
View File
@@ -63,9 +63,9 @@ Given that there are couple of music files, simplest usage is as follows:
$ flac2ogg.py directory_of_music_files/* $ flac2ogg.py directory_of_music_files/*
All files from that directory will be encoded to *opus* by default. If there All files from that directory will be encoded to *opus* by default. If there
are already some *opus* files, new files would have ``_encoded_`` added into are already *opus* files with exactly same name, new files would have
the filename. Note, that output files will be placed next to the original ``_encoded_`` added into the filename, leaving existing files intact. Note,
files. that output files will be placed next to the original files.
License License
======= =======
+151 -53
View File
@@ -3,6 +3,7 @@
Audio file converter. Audio file converter.
""" """
import argparse import argparse
import base64
import multiprocessing as mp import multiprocessing as mp
import os import os
import re import re
@@ -10,11 +11,13 @@ import subprocess as sp
import sys import sys
import mutagen import mutagen
from mutagen.mp3 import MP3 import mutagen.easyid3
from mutagen.easyid3 import EasyID3, EasyID3KeyError import mutagen.flac
import mutagen.id3
import mutagen.mp3
VERSION = '1.3.1' VERSION = '1.4.0'
def match_file(path): def match_file(path):
@@ -105,6 +108,150 @@ class CueObjectParser:
continue continue
class Tag:
def __init__(self, source_file, destination_file):
self.pictures = []
self.tags = {}
if destination_file.lower().endswith(".mp3"):
dest = self._tag_mp3
if (destination_file.lower().endswith(".ogg") or
destination_file.lower().endswith(".opus")):
dest = self._tag_ogg
if source_file.lower().endswith(".mp3"):
self._extract_mp3_tags(source_file)
if source_file.lower().endswith(".flac"):
self._extract_flac_tags(source_file)
if (source_file.lower().endswith(".ogg") or
source_file.lower().endswith(".opus")):
self._extract_ogg_tags(source_file)
dest(destination_file)
def _tag_mp3(self, dest):
tags = mutagen.mp3.MP3(dest, ID3=mutagen.easyid3.EasyID3)
if self.tags:
for key in ['album', 'albumartist', 'artist', 'composer',
'copyright', 'date', 'discnumber', 'encoded-by',
'genre', 'title', 'tracknumber']:
if key not in self.tags:
continue
if key == 'encoded-by':
tags['encodedby'] = self.tags[key]
else:
tags[key] = self.tags[key]
if 'tracknumber' in self.tags and 'tracktotal' in self.tags:
tags['tracknumber'] = [(f"{self.tags['tracknumber'][0]}"
f"/{self.tags['tracktotal'][0]}")]
tags.save()
tags = mutagen.id3.ID3(dest)
for key in ('contact', 'description', 'performer'):
if key not in self.tags:
continue
if key == 'contact':
tags.add(mutagen.id3.WXXX(url=self.tags[key][0]))
if key == 'description':
tags.add(mutagen.id3.COMM(text=self.tags[key]))
if key == 'performer':
tags.add(mutagen.id3.TOPE(text=self.tags[key]))
for pic in self.pictures:
tags.add(mutagen.id3.APIC(encoding=3, mime=pic.mime, type=pic.type,
desc=pic.desc, data=pic.data))
tags.save()
def _tag_ogg(self, dest):
tags = mutagen.File(dest)
if self.tags:
tags.update(self.tags)
if self.pictures:
tags['metadata_block_picture'] = [base64.b64encode(pic.write())
.decode('ascii')
for pic in self.pictures]
tags.save()
def _extract_flac_tags(self, source):
"""Extract all embedded pictures from FLAC."""
tags = mutagen.flac.FLAC(source)
self.tags = dict(tags)
self.pictures = tags.pictures
def _extract_ogg_tags(self, source):
"""Extract pictures from OGG Vorbis or OGG Opus."""
tags = mutagen.File(source)
self.tags = dict(tags)
for x in ['metadata_block_picture', 'coverart', 'coverartmime']:
if x in self.tags:
del self.tags[x]
for encoded in tags.get("metadata_block_picture", []):
try:
raw = base64.b64decode(encoded, validate=True)
picture = mutagen.flac.Picture(raw)
self.pictures.append(picture)
except (ValueError, TypeError, mutagen.flac.FLACError):
continue
# Legacy coverart convention used by some applications.
if not self.pictures:
for encoded, mime in zip(tags.get("coverart", []),
tags.get("coverartmime", [])):
try:
raw = base64.b64decode(encoded, validate=True)
picture = mutagen.flac.Picture()
picture.data = raw
picture.mime = mime or "image/jpeg"
picture.type = 3
picture.desc = ""
self.pictures.append(picture)
except (ValueError, TypeError):
continue
def _extract_mp3_tags(self, source):
"""get all mp3 tags, and store it as a unified dict"""
tags = mutagen.mp3.MP3(source, ID3=mutagen.easyid3.EasyID3)
if tags.get('tracknumber'):
if '/' in tags['tracknumber'][0]:
tn, tt = tags['tracknumber'][0].split('/')
self.tags['tracknumber'], self.tags['tracktotal'] = [tn], [tt]
else:
self.tags['tracknumber'] = tags['tracknumber']
if tags.get('encodedby'):
self.tags['encoded-by'] = tags['encodedby']
for key in ['album', 'albumartist', 'artist', 'composer', 'copyright',
'date', 'discnumber', 'genre', 'title']:
if key in tags:
self.tags[key] = tags[key]
tags = mutagen.id3.ID3(source)
if tags.get('WXXX:'):
self.tags['contact'] = [tags['WXXX:'].url]
if tags.getall('COMM'):
self.tags['description'] = tags.getall('COMM')[0].text
if tags.get('TOPE'):
self.tags['performer'] = tags['TOPE'].text
if tags is None:
return
for frame in tags.getall("APIC"):
picture = mutagen.flac.Picture()
picture.data = frame.data
picture.mime = frame.mime
picture.type = frame.type
picture.desc = frame.desc
self.pictures.append(picture)
class Encoder: class Encoder:
"""Encoder base class""" """Encoder base class"""
EXT = ".undefined" EXT = ".undefined"
@@ -214,56 +361,7 @@ class FileType:
def _tag_file(self): def _tag_file(self):
"""Transfer tags from source files, or from cue""" """Transfer tags from source files, or from cue"""
Tag(self.filename, self.out_fname)
if self.ext == '.mp3':
tag = MP3(self.filename, ID3=EasyID3)
else:
tag = mutagen.File(self.filename)
if isinstance(self.encoder, Mp3Encoder):
self._mp3_tag(tag)
return
out_tag = mutagen.File(self.out_fname)
if self.album:
out_tag['album'] = self.album
if self.album_artist:
out_tag['albumartist'] = self.album_artist
if self.performer:
out_tag['artist'] = self.performer
if self.title:
out_tag['title'] = self.title
out_tag.save()
try:
out_tag.update(tag)
out_tag.save()
except:
pass
def _mp3_tag(self, tag):
"""Special case of tagging mp3 output file"""
mp3_tag = MP3(self.out_fname, ID3=EasyID3)
mp3_tag.add_tags(ID3=EasyID3)
if self.album:
mp3_tag['album'] = self.album
if self.performer:
mp3_tag['artist'] = self.performer
if self.title:
mp3_tag['title'] = self.title
mp3_tag.save()
for key, val in tag.items():
try:
if isinstance(val, list):
mp3_tag[key] = ", ".join(val)
else:
mp3_tag[key] = val
except EasyID3KeyError:
pass # ignore unknown keys
mp3_tag.save()
class FlacType(FileType): class FlacType(FileType):