Извлечь обложку из аудиофайла
Достаёт встроенную обложку из MP3, FLAC, M4A и OGG в отдельный JPEG или PNG.
Что делает скрипт
Скрипт читает теги через mutagen и сохраняет картинки в папку covers. Поддерживает несколько обложек в одном файле, повторы отбрасываются по SHA-1. Оригинальные аудиофайлы не изменяются.
Быстрый старт
python extract_cover.py album.mp3 --out ./covers
Скачайте файл, откройте терминал в папке со скриптом и выполните команду.
В Linux и macOS интерпретатор может называться python3, в Windows - python или py.
Другие варианты
python extract_cover.py track.flacpython extract_cover.py ./music --recursive --out ./art
Что понадобится
winget install Python.Python.3.12
brew install python
sudo apt install python3
py -m pip install mutagen
python3 -m pip install mutagen
python3 -m pip install mutagen
extract_cover.py
#!/usr/bin/env python3
"""Извлечение встроенных обложек из аудиофайлов."""
from __future__ import annotations
import argparse
import base64
import hashlib
import sys
from pathlib import Path
from mutagen import File as MutagenFile
from mutagen.flac import Picture
from mutagen.id3 import APIC
from mutagen.mp3 import MP3
from mutagen.mp4 import MP4, MP4Cover
AUDIO_EXTENSIONS = {'.mp3', '.flac', '.m4a', '.mp4', '.ogg', '.oga'}
def collect(paths: list[Path], recursive: bool) -> list[Path]:
files: list[Path] = []
for path in paths:
if path.is_dir():
iterator = path.rglob('*') if recursive else path.glob('*')
files.extend(
item for item in iterator
if item.is_file() and item.suffix.lower() in AUDIO_EXTENSIONS
)
elif path.is_file() and path.suffix.lower() in AUDIO_EXTENSIONS:
files.append(path)
else:
print(f'Пропуск: {path}', file=sys.stderr)
return sorted(set(files), key=lambda item: str(item).lower())
def cover_list(audio) -> list[tuple[str, bytes]]:
result: list[tuple[str, bytes]] = []
if isinstance(audio, MP3):
if audio.tags:
for frame in audio.tags.values():
if isinstance(frame, APIC):
result.append((frame.mime, bytes(frame.data)))
elif isinstance(audio, MP4):
if audio.tags:
for item in audio.tags.get('covr', []):
mime = 'image/png' if item.imageformat == MP4Cover.FORMAT_PNG else 'image/jpeg'
result.append((mime, bytes(item)))
elif hasattr(audio, 'pictures'):
for picture in audio.pictures:
result.append((picture.mime or 'image/jpeg', bytes(picture.data)))
elif audio.tags:
values = audio.tags.get('metadata_block_picture', [])
for value in values:
try:
picture = Picture(base64.b64decode(value))
except Exception:
continue
result.append((picture.mime or 'image/jpeg', bytes(picture.data)))
return result
def extension_for(mime: str) -> str:
mime = (mime or '').lower()
if 'png' in mime:
return '.png'
if 'webp' in mime:
return '.webp'
if 'gif' in mime:
return '.gif'
return '.jpg'
def main() -> int:
parser = argparse.ArgumentParser(description='Извлечь обложки из аудио')
parser.add_argument('inputs', nargs='+', type=Path, help='Файлы или папки')
parser.add_argument('-o', '--out', type=Path, default=Path('covers'), help='Папка для обложек')
parser.add_argument('--recursive', action='store_true', help='Обходить вложенные папки')
parser.add_argument('--overwrite', action='store_true', help='Перезаписать существующие файлы')
args = parser.parse_args()
files = collect([path.expanduser() for path in args.inputs], args.recursive)
if not files:
print('Аудиофайлы не найдены.', file=sys.stderr)
return 1
out_dir = args.out.expanduser().resolve()
out_dir.mkdir(parents=True, exist_ok=True)
seen: set[str] = set()
saved = 0
empty = 0
for source in files:
audio = MutagenFile(source)
if audio is None:
print(f'Формат не поддержан: {source.name}', file=sys.stderr)
continue
covers = cover_list(audio)
if not covers:
print(f'Нет обложки: {source.name}')
empty += 1
continue
for index, (mime, data) in enumerate(covers, start=1):
digest = hashlib.sha1(data).hexdigest()
if digest in seen:
continue
seen.add(digest)
suffix = extension_for(mime)
name = source.stem if len(covers) == 1 else f'{source.stem}-{index}'
destination = out_dir / f'{name}{suffix}'
if destination.exists() and not args.overwrite:
print(f'Пропуск: {destination}')
continue
destination.write_bytes(data)
print(f'Готово: {destination}')
saved += 1
print(f'Итог: сохранено {saved}, файлов без обложки {empty}')
return 0 if saved or empty == 0 else 1
if __name__ == '__main__':
raise SystemExit(main())
Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.