#!/usr/bin/env python3 """Переименование аудиофайлов по значениям тегов.""" from __future__ import annotations import argparse import re import string import sys from pathlib import Path from mutagen import File as MutagenFile from mutagen.flac import FLAC from mutagen.mp3 import MP3 from mutagen.mp4 import MP4 from mutagen.oggvorbis import OggVorbis AUDIO_EXTENSIONS = {'.mp3', '.flac', '.m4a', '.mp4', '.ogg', '.oga'} ALLOWED_FIELDS = {'artist', 'title', 'album', 'track', 'year', 'genre'} MP3_KEYS = { 'title': 'TIT2', 'artist': 'TPE1', 'album': 'TALB', 'track': 'TRCK', 'year': 'TDRC', 'genre': 'TCON', } MP4_KEYS = { 'title': '\xa9nam', 'artist': '\xa9ART', 'album': '\xa9alb', 'year': '\xa9day', 'genre': '\xa9gen', } 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 read_tags(path: Path) -> dict[str, str]: audio = MutagenFile(path) values: dict[str, str] = {} if audio is None: return values if isinstance(audio, MP3): if audio.tags: for name, key in MP3_KEYS.items(): frame = audio.tags.get(key) if frame is not None: values[name] = str(frame).strip() elif isinstance(audio, MP4): if audio.tags: for name, key in MP4_KEYS.items(): data = audio.tags.get(key) if data: values[name] = str(data[0]).strip() track = audio.tags.get('trkn') if track: values['track'] = str(track[0][0]) elif isinstance(audio, (FLAC, OggVorbis)): for name in ALLOWED_FIELDS: data = audio.get(name) if data: values[name] = str(data[0]).strip() for name in ('title', 'artist', 'album', 'genre'): if name in values: values[name] = ' '.join(values[name].split()) if values.get('track'): values['track'] = values['track'].split('/')[0].strip() if values['track'].isdigit(): values['track'] = values['track'].zfill(2) if values.get('year'): match = re.match(r'(\d{4})', values['year']) values['year'] = match.group(1) if match else '' return values def safe_name(value: str) -> str: value = re.sub(r'[<>:"/\\|?*\x00-\x1f]', '_', value) value = ' '.join(value.split()) return value.strip(' .')[:180] def main() -> int: parser = argparse.ArgumentParser(description='Переименовать треки по тегам') parser.add_argument('inputs', nargs='+', type=Path, help='Файлы или папки') parser.add_argument('--pattern', default='{artist} - {title}', help='Шаблон имени без расширения') parser.add_argument('--recursive', action='store_true', help='Обходить вложенные папки') parser.add_argument('--apply', action='store_true', help='Выполнить переименование') args = parser.parse_args() fields = { field for _, field, _, _ in string.Formatter().parse(args.pattern) if field is not None } unknown = fields - ALLOWED_FIELDS if unknown: parser.error(f'Неизвестные поля шаблона: {", ".join(sorted(unknown))}') files = collect([path.expanduser() for path in args.inputs], args.recursive) if not files: print('Аудиофайлы не найдены.', file=sys.stderr) return 1 planned: set[Path] = set() renamed = 0 skipped = 0 missing = 0 for source in files: tags = read_tags(source) absent = sorted(field for field in fields if not tags.get(field)) if absent: print(f'Нет тегов {", ".join(absent)}: {source}') missing += 1 continue try: base = args.pattern.format_map(tags) except (KeyError, ValueError) as error: print(f'Ошибка шаблона для {source.name}: {error}', file=sys.stderr) skipped += 1 continue new_base = safe_name(base) if not new_base: print(f'Пустое имя после очистки: {source}') skipped += 1 continue destination = source.with_name(f'{new_base}{source.suffix}') if destination == source: print(f'Уже совпадает: {source.name}') skipped += 1 continue if destination in planned or destination.exists(): print(f'Конфликт имени: {destination}') skipped += 1 continue planned.add(destination) if args.apply: source.rename(destination) print(f'Переименовано: {source.name} -> {destination.name}') renamed += 1 else: print(f'Будет: {source.name} -> {destination.name}') if not args.apply: print('Это предпросмотр. Для переименования добавьте --apply.') print(f'Итог: переименовано {renamed}, пропущено {skipped}, без тегов {missing}') return 0 if __name__ == '__main__': raise SystemExit(main())