Удалить теги из аудиофайлов
Очищает ID3, FLAC, MP4 и OGG теги в копиях, при желании сохраняя обложку.
Что делает скрипт
Скрипт копирует файлы в отдельную папку и удаляет из копий все метаданные через mutagen. Обложку можно сохранить флагом --keep-cover. Оригиналы не изменяются, существующие файлы в папке результата пропускаются.
Быстрый старт
python strip_tags.py ./music --out ./clean
Скачайте файл, откройте терминал в папке со скриптом и выполните команду.
В Linux и macOS интерпретатор может называться python3, в Windows - python или py.
Другие варианты
python strip_tags.py album.flacpython strip_tags.py ./music --recursive --keep-cover
Что понадобится
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
strip_tags.py
#!/usr/bin/env python3
"""Удаление музыкальных тегов в копиях файлов."""
from __future__ import annotations
import argparse
import shutil
import sys
from pathlib import Path
from mutagen import File as MutagenFile
from mutagen.flac import FLAC
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 save_covers(audio) -> tuple[str, list]:
if isinstance(audio, MP3):
if audio.tags is None:
return 'mp3', []
return 'mp3', [frame for frame in audio.tags.values() if isinstance(frame, APIC)]
if isinstance(audio, FLAC):
return 'flac', list(audio.pictures)
if isinstance(audio, MP4):
covers = []
if audio.tags:
for item in audio.tags.get('covr', []):
image_format = MP4Cover.FORMAT_PNG if item.imageformat == MP4Cover.FORMAT_PNG else MP4Cover.FORMAT_JPEG
covers.append(MP4Cover(bytes(item), imageformat=image_format))
return 'mp4', covers
return 'other', []
def restore_covers(audio, kind: str, covers: list) -> None:
if not covers:
return
if kind == 'mp3':
if audio.tags is None:
audio.add_tags()
for frame in covers:
audio.tags.add(frame)
elif kind == 'flac':
for picture in covers:
audio.add_picture(picture)
elif kind == 'mp4':
if audio.tags is None:
audio.add_tags()
audio.tags['covr'] = covers
def main() -> int:
parser = argparse.ArgumentParser(description='Удалить теги из аудиофайлов')
parser.add_argument('inputs', nargs='+', type=Path, help='Файлы или папки')
parser.add_argument('-o', '--out', type=Path, default=Path('clean_tags'), help='Папка для копий')
parser.add_argument('--recursive', action='store_true', help='Обходить вложенные папки')
parser.add_argument('--keep-cover', 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)
done = skipped = failed = 0
for source in files:
destination = out_dir / source.name
if destination.exists() and not args.overwrite:
print(f'Пропуск: {destination}')
skipped += 1
continue
shutil.copy2(source, destination)
audio = MutagenFile(destination)
if audio is None:
print(f'Формат не поддержан: {source.name}', file=sys.stderr)
failed += 1
continue
kind, covers = save_covers(audio) if args.keep_cover else ('other', [])
try:
audio.delete()
restore_covers(audio, kind, covers)
audio.save()
except Exception as error:
print(f'Ошибка {source.name}: {error}', file=sys.stderr)
failed += 1
continue
print(f'Готово: {source.name}')
done += 1
print(f'Итог: готово {done}, пропущено {skipped}, ошибок {failed}')
return 0 if failed == 0 else 2
if __name__ == '__main__':
raise SystemExit(main())
Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.