#!/usr/bin/env python3 """Собирает плейлисты для тренировки по тегу BPM.""" from __future__ import annotations import argparse import re from pathlib import Path from mutagen import File as MutagenFile AUDIO_EXTENSIONS = {".mp3", ".flac", ".m4a", ".ogg", ".opus", ".wav"} BPM_IN_NAME = re.compile(r"(?i)(\d{2,3})\s*bpm") RANGES = [ ("warmup", 90, 120), ("cardio", 120, 150), ("peak", 150, 180), ] def read_bpm(path: Path) -> int | None: try: audio = MutagenFile(path, easy=True) except Exception: audio = None if audio is not None and audio.tags: raw = audio.tags.get("bpm") if isinstance(raw, list): raw = raw[0] if raw else None if raw is not None: match = re.search(r"\d{2,3}", str(raw)) if match: return int(match.group(0)) match = BPM_IN_NAME.search(path.stem) if match: return int(match.group(1)) return None def main() -> int: parser = argparse.ArgumentParser(description="Плейлисты по BPM") parser.add_argument("--dir", type=Path, required=True, help="Папка с музыкой") parser.add_argument("--out", type=Path, default=Path("workout"), help="Папка для M3U") parser.add_argument("--apply", action="store_true", help="Записать плейлисты") parser.add_argument("--force", action="store_true", help="Перезаписать M3U") args = parser.parse_args() root = args.dir.expanduser().resolve() if not root.is_dir(): parser.error(f"Папка не найдена: {root}") output = args.out.expanduser().resolve() buckets: dict[str, list[tuple[Path, int]]] = {name: [] for name, _, _ in RANGES} without = 0 outside = 0 for path in sorted(root.rglob("*")): if not path.is_file() or path.suffix.lower() not in AUDIO_EXTENSIONS: continue bpm = read_bpm(path) if bpm is None: without += 1 continue matched = False for name, low, high in RANGES: if name == "peak" and low <= bpm <= high: buckets[name].append((path, bpm)) matched = True break if name != "peak" and low <= bpm < high: buckets[name].append((path, bpm)) matched = True break if not matched: outside += 1 for name, low, high in RANGES: print(f"{name}: {len(buckets[name])} треков ({low}-{high} BPM)") print(f"Без BPM: {without}, вне диапазонов: {outside}") if not args.apply: print("Это предпросмотр. Для записи добавьте --apply.") return 0 output.mkdir(parents=True, exist_ok=True) for name, _, _ in RANGES: target = output / f"workout-{name}.m3u" if target.exists() and not args.force: print(f"Пропуск, файл существует: {target}") continue lines = ["#EXTM3U"] for path, bpm in buckets[name]: lines.append(f"#EXTINF:-1,{path.stem} [{bpm} BPM]") lines.append(str(path)) target.write_text("\n".join(lines) + "\n", encoding="utf-8") print(f"Сохранено: {target}") return 0 if __name__ == "__main__": raise SystemExit(main())