Files
buryan-infra/ops/media/music_tools.py
buryan-agent 7e0afefbe1 Lidarr и beets: управление музыкой, теги, дубли
Lidarr 3.1.0 в CT 111 (192.168.1.240:8686): корневая папка /music,
qBittorrent с категорией lidarr, синхронизация индексаторов из Prowlarr.
Образ через ghcr.nju.edu.cn (lscr.io тянется слишком медленно), host-сеть
(-p не пробрасывал порт).

music_tools.py: --status, --import (beets), --enrich (MusicBrainz),
--dupes (fpcalc). Команда «музыка» показывает Navidrome, библиотеку, Lidarr
и наличие токена Яндекса.

Ловушки: адрес CT 111 — 192.168.1.240; f-string ломается на шаблоне beets
с фигурными скобками.
2026-10-20 13:38:10 +03:00

180 lines
5.6 KiB
Python

"""Музыкальные инструменты: импорт, обогащение, поиск дублей, плейлисты.
Обёртка над beets (теги и структура), fpcalc (отпечатки) и Navidrome (M3U).
"""
import json
import os
import subprocess
import sys
VENV = "/opt/music-tools/venv"
BEET = VENV + "/bin/beet"
MUSIC = os.environ.get("MUSIC_DIR", "/mnt/media/music")
CONFIG = "/root/.config/beets/config.yaml"
def run(cmd, timeout=600):
try:
p = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout)
return (p.stdout or "") + (p.stderr or "")
except subprocess.TimeoutExpired:
return "таймаут"
def ensure_config():
os.makedirs(os.path.dirname(CONFIG), exist_ok=True)
if not os.path.exists(CONFIG):
with open(CONFIG, "w", encoding="utf-8") as f:
cfg = (
"directory: " + MUSIC + "\n"
"library: /root/.config/beets/library.db\n"
"\n"
"import:\n"
" write: yes\n"
" move: yes\n"
" autotag: yes\n"
" quiet: no\n"
"\n"
"paths:\n"
" default: $albumartist/$album%aunique{}/$track $title\n"
"\n"
"plugins: musicbrainz\n"
"musicbrainz:\n"
" auto: yes\n"
)
f.write(cfg)
return CONFIG
def cmd_status():
print("=== БИБЛИОТЕКА ===")
if not os.path.isdir(MUSIC):
print(" нет папки", MUSIC)
return 1
albums = 0
tracks = 0
for artist in os.listdir(MUSIC):
ap = os.path.join(MUSIC, artist)
if not os.path.isdir(ap):
continue
for album in os.listdir(ap):
bp = os.path.join(ap, album)
if not os.path.isdir(bp):
continue
files = [f for f in os.listdir(bp)
if f.lower().endswith((".mp3", ".flac", ".ogg", ".m4a", ".wav"))]
if files:
albums += 1
tracks += len(files)
print(f" альбомов: {albums}, треков: {tracks}")
print("\n=== BEETS ===")
print(" " + run([BEET, "version"]).splitlines()[0])
print("\n=== LIDARR ===")
key = None
try:
out = subprocess.run(
["pct", "exec", "111", "--", "docker", "exec", "lidarr", "sh", "-c",
"grep -o '<ApiKey>[^<]*' /config/config.xml"],
capture_output=True, text=True, timeout=30).stdout
if "<ApiKey>" in out:
key = out.split("<ApiKey>")[1].strip()
except Exception:
key = None
if not key:
print(" Lidarr: ключ не получен")
return 0
try:
import urllib.request
req = urllib.request.Request("http://192.168.1.240:8686/api/v1/system/status",
headers={"X-Api-Key": key})
with urllib.request.urlopen(req, timeout=10) as r:
data = json.loads(r.read() or b"{}")
print(" Lidarr: версия", data.get("version"))
req2 = urllib.request.Request("http://192.168.1.240:8686/api/v1/artist",
headers={"X-Api-Key": key})
with urllib.request.urlopen(req2, timeout=15) as r:
artists = json.loads(r.read() or b"[]")
print(" артистов в Lidarr:", len(artists))
except Exception as e:
print(" Lidarr: ошибка", str(e)[:60])
return 0
def cmd_import(path=None):
ensure_config()
src = path or MUSIC
print(f"=== ИМПОРТ: {src} ===")
out = run([BEET, "import", "-q", src], timeout=1800)
tail = [l for l in out.splitlines() if l.strip()][-8:]
for l in tail:
print(" " + l[:120])
return 0
def cmd_enrich():
ensure_config()
print("=== ОБОГАЩЕНИЕ ТЕГАМИ (MusicBrainz) ===")
out = run([BEET, "update", "-q"], timeout=1800)
for l in [x for x in out.splitlines() if x.strip()][-8:]:
print(" " + l[:120])
return 0
def cmd_dupes():
print("=== ПОИСК ДУБЛЕЙ (отпечатки) ===")
seen = {}
dupes = []
for root, _d, files in os.walk(MUSIC):
for f in files:
if not f.lower().endswith((".mp3", ".flac", ".ogg", ".m4a")):
continue
path = os.path.join(root, f)
out = run(["fpcalc", "-raw", path], timeout=120)
if "FINGERPRINT=" not in out:
continue
fp = out.split("FINGERPRINT=")[-1].strip()[:120]
if fp in seen:
dupes.append((seen[fp], path))
else:
seen[fp] = path
if not dupes:
print(" дублей не найдено")
return 0
for a, b in dupes:
print(" дубль:\n " + a + "\n " + b)
return 0
def cmd_playlist(name, paths):
dest = os.path.join(MUSIC, name + ".m3u")
with open(dest, "w", encoding="utf-8") as f:
f.write("#EXTM3U\n")
for p in paths:
f.write(os.path.relpath(p, MUSIC) + "\n")
print(" плейлист:", dest, "треков:", len(paths))
return 0
def main():
args = sys.argv[1:]
if not args:
print(__doc__)
return 0
mode = args[0]
if mode == "--status":
return cmd_status()
if mode == "--import":
return cmd_import(args[1] if len(args) > 1 else None)
if mode == "--enrich":
return cmd_enrich()
if mode == "--dupes":
return cmd_dupes()
print("неизвестный режим:", mode)
return 2
if __name__ == "__main__":
sys.exit(main())