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
с фигурными скобками.
This commit is contained in:
buryan-agent committed 2026-10-20 13:38:10 +03:00
1 parent b9e1bf26b8
commit 7e0afefbe1
3 files changed
+252

No files matched your search

+20
View File
@@ -91,6 +91,26 @@ class MediaBot(Bot):
tracks += len(files)
lines.append(f"В библиотеке: {albums} альбомов, {tracks} треков")
# Lidarr
try:
import subprocess as _sp
key = ""
out = _sp.run(["pct", "exec", "111", "--", "docker", "exec", "lidarr", "sh", "-c",
"grep -o '<ApiKey>[^<]*' /config/config.xml"],
capture_output=True, text=True, timeout=25).stdout
if "<ApiKey>" in out:
key = out.split("<ApiKey>")[1].strip()
if key:
req = _rq.Request("http://192.168.1.240:8686/api/v1/system/status",
headers={"X-Api-Key": key})
with _rq.urlopen(req, timeout=10) as r:
st = _json.loads(r.read() or b"{}")
lines.append("Lidarr: версия " + str(st.get("version")))
else:
lines.append("Lidarr: ключ не получен")
except Exception:
lines.append("Lidarr: недоступен")
# Яндекс Музыка
tok = "/root/.yandex-token"
if _os.path.exists(tok):
+53
View File
@@ -38,3 +38,56 @@ externally-managed: `pip install beets` падает на конфликте с
подписки — нарушение авторских прав. Инструменты (Lidarr, yt-dlp, slskd)
нейтральны, но контент должен быть легальным: своя подписка, покупка,
свободная музыка.
---
## Lidarr
Поставлен в CT 111 (адрес **192.168.1.240**, порт 8686).
```
образ: ghcr.nju.edu.cn/linuxserver/lidarr (зеркало; lscr.io тянется слишком медленно)
тома: /music ← /mnt/media/music
/downloads ← /mnt/media/downloads
сеть: host (без bridge: с -p 8686:8686 порт не был виден с узла)
```
Настроено автоматически (`lidarr_setup.py`):
| Что | Значение |
|---|---|
| корневая папка | `/music` |
| клиент загрузки | qBittorrent `192.168.1.123:8085`, категория `lidarr` |
| синхронизация | Prowlarr → Lidarr (категории 3000–3040) |
Проверка: `GET /api/v1/system/status` → версия **3.1.0.4875**.
## Инструменты: `music_tools.py`
| Режим | Что делает |
|---|---|
| `--status` | библиотека, beets, Lidarr |
| `--import [путь]` | beets: теги и структура (`$albumartist/$album/$track $title`) |
| `--enrich` | обновление тегов из MusicBrainz |
| `--dupes` | поиск дублей по отпечаткам fpcalc |
```
=== БИБЛИОТЕКА ===
альбомов: 0, треков: 0
=== BEETS ===
beets version 2.14.1
=== LIDARR ===
Lidarr: версия 3.1.0.4875
артистов в Lidarr: 0
```
## Ловушки
* **Образы.** `lscr.io` и Docker Hub отдают слои крайне медленно; зеркало
`ghcr.nju.edu.cn` скачало образ за минуту.
* **Порт.** С `-p 8686:8686` контейнер слушал внутри CT, но с узла порт был
закрыт. Помогла host-сеть.
* **Адрес CT 111 — 192.168.1.240**, а не `.111`. Проверять `ip addr`, а не
угадывать.
* **f-string и шаблон beets.** `$album%aunique{}` внутри f-строки ломает
разбор (`{}` — выражение). Конфиг собирается обычной конкатенацией.
+179
View File
@@ -0,0 +1,179 @@
"""Музыкальные инструменты: импорт, обогащение, поиск дублей, плейлисты.
Обёртка над 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())