refactor(music)!: make Song an ordinary Title on the generic path

Delete the dead grouped-download block, the planner, and the music service hooks; Song now flows through the one download loop, gets tagged via tag_file, and answers -w with {disc}x{track} keys.

BREAKING CHANGE: GROUP_AUDIO_DOWNLOADS, get_music_track_options and get_music_collection_label are gone. A music service returns one Audio track per quality and lets the framework choose.
This commit is contained in:
imSp4rky
2026-08-18 15:05:30 -06:00
parent a4a385e5aa
commit 68c7d95173
43 changed files with 1082 additions and 2132 deletions
-23
View File
@@ -1,8 +1,6 @@
from .display import MusicHeaderInfo, TrackRow, render_album_header, render_artwork_preview, render_track_panel
from .extract import (
build_music_from_songs,
classify_release_kind,
dedupe_track_options,
duration_seconds,
first_number,
first_text,
@@ -10,40 +8,19 @@ from .extract import (
format_names,
year_from_value,
)
from .hasher import file_md5
from .integrity import MusicAudioIntegrityError, MusicAudioIntegrityResult, verify_music_audio
from .manifest import write_music_manifest
from .models import MusicDiscPlan, MusicDownloadPlan, MusicSongPlan, MusicTrackOption
from .planner import MusicPlanner
from .renderer import MusicRenderer
from .tagger import MusicMetadataResult, write_music_metadata
__all__ = (
"MusicAudioIntegrityError",
"MusicAudioIntegrityResult",
"MusicDiscPlan",
"MusicDownloadPlan",
"MusicHeaderInfo",
"MusicMetadataResult",
"MusicPlanner",
"MusicRenderer",
"MusicSongPlan",
"MusicTrackOption",
"TrackRow",
"build_music_from_songs",
"classify_release_kind",
"dedupe_track_options",
"duration_seconds",
"file_md5",
"first_number",
"first_text",
"format_duration",
"format_names",
"render_album_header",
"render_artwork_preview",
"render_track_panel",
"verify_music_audio",
"write_music_manifest",
"write_music_metadata",
"year_from_value",
)
-174
View File
@@ -1,174 +0,0 @@
"""Shared rich-based rendering helpers for music releases.
Data-in / renderable-out: services do their own quality and field extraction,
then hand plain data here. The helpers know nothing about how a ``quality_label``
was derived; they only style and lay it out. Quality-schema parsing stays
per-service while panel/header/artwork rendering lives in one place.
"""
from __future__ import annotations
import re
from dataclasses import dataclass
from io import BytesIO
from typing import Any, Optional
from rich import box
from rich.console import Group, RenderableType
from rich.padding import Padding
from rich.panel import Panel
from rich.table import Table
from rich.text import Text
from rich.tree import Tree
from unshackle.core.titles.music import Song
@dataclass
class TrackRow:
"""One row in the track tree, already formatted by the calling service.
When ``note`` is set the row is treated as unavailable: the quality label is
styled red, ``note`` is appended muted, and the ``cd``/``hires`` badges are
suppressed. Otherwise the normal detail line is built and ``cd`` drives a
"CD" badge.
"""
song: Song
quality_label: str
layout: str
duration_str: str
hires: bool = False
cd: bool = False
note: str = ""
@dataclass
class MusicHeaderInfo:
"""Plain data holder for the release-header metadata grid."""
artist: str
album: str
year: str
track_count: int
quality_label: str
duration_str: str = ""
artist_label: str = "Artist"
# Quality strings look like "FLAC 16-bit/44.1kHz"; split the codec token off the
# front and bracket it so the detail line reads "[FLAC] | 16-bit/44.1kHz".
QUALITY_DETAIL_RE = re.compile(r"^(FLAC|OGG|AAC|MP3)\s+(.+)$", flags=re.IGNORECASE)
def format_track_detail_quality(quality_label: str) -> str:
"""Bracket the leading codec token of a quality string for the detail line."""
text = str(quality_label or "").strip()
match = QUALITY_DETAIL_RE.match(text)
if match:
return f"[{match.group(1).upper()}] | {match.group(2).strip()}"
return text
def render_artwork_preview(
session: Any,
artwork_url: str,
*,
width: int = 25,
) -> Optional[RenderableType]:
"""Fetch artwork via ``session`` and render it as half-block coloured cells.
Pillow (``PIL``) is an optional dependency; any error (missing PIL, network,
bad image, zero dimensions) soft-fails to ``None`` so callers skip the preview.
"""
if not artwork_url:
return None
try:
from PIL import Image
except Exception:
return None
try:
response = session.get(artwork_url, timeout=20)
response.raise_for_status()
image = Image.open(BytesIO(response.content)).convert("RGB")
if not image.width or not image.height:
return None
height = max(1, int(width * image.height / image.width * 0.5))
# Image.Resampling exists on Pillow >= 9.1; fall back gracefully on older.
resampling = getattr(getattr(Image, "Resampling", Image), "LANCZOS", 1)
image = image.resize((width, height * 2), resampling)
lines = []
for y in range(0, image.height, 2):
line = Text()
for x in range(image.width):
top = image.getpixel((x, y))
bottom = image.getpixel((x, min(y + 1, image.height - 1)))
top_color = f"#{top[0]:02x}{top[1]:02x}{top[2]:02x}"
bottom_color = f"#{bottom[0]:02x}{bottom[1]:02x}{bottom[2]:02x}"
# Lower-half block fg=bottom/bg=top packs two pixel rows per cell.
line.append("▄", style=f"{bottom_color} on {top_color}")
lines.append(line)
return Group(*lines)
except Exception:
return None
def render_track_panel(rows: list[TrackRow], total: int) -> Panel:
"""Render the per-track tree (one node + detail line each) in a Panel."""
track_label = "Track" if total == 1 else "Tracks"
tree = Tree(f"[repr.number]{total}[/] {track_label}", guide_style="bright_black")
for row in rows:
title_line = Text(f"{row.song.track:02}", style="repr.number")
title_line.append(" ")
title_line.append(row.song.name, style="bold #009900")
node = tree.add(title_line, guide_style="bright_black")
detail = Text()
if row.note:
detail.append(row.quality_label, style="red")
detail.append(" ")
detail.append(row.note, style="bright_black")
else:
detail.append(format_track_detail_quality(row.quality_label))
if row.layout:
detail.append(" | ")
detail.append(row.layout)
if row.duration_str:
detail.append(" | ")
detail.append(row.duration_str)
if row.cd:
detail.append(" | ")
detail.append("CD", style="yellow1")
if row.hires:
detail.append(" | ")
detail.append("Hi-Res", style="gold1")
node.add(detail, guide_style="bright_black")
return Panel(tree, title="Available Tracks", box=box.SQUARE, border_style="bright_black")
def render_album_header(
info: MusicHeaderInfo,
artwork: Optional[RenderableType] = None,
) -> Optional[RenderableType]:
"""Render the release metadata grid, optionally placing artwork beside it."""
grid = Table.grid(padding=(0, 2))
grid.add_column(style="orchid1", no_wrap=True)
grid.add_column()
grid.add_row(info.artist_label, Text(info.artist, style="bold #ff0000"))
grid.add_row("Collection", Text(info.album, style="blue"))
grid.add_row("Year", Text(info.year, style="blue"))
grid.add_row("Tracks", Text(str(info.track_count), style="blue"))
grid.add_row("Quality", Text(info.quality_label, style="blue"))
if info.duration_str:
grid.add_row("Length", Text(info.duration_str, style="blue"))
if not artwork:
return grid
header = Table.grid(expand=True, padding=(0, 2))
header.add_column(no_wrap=True)
header.add_column(ratio=1)
header.add_row(artwork, Padding(grid, (3, 0, 0, 0)))
return header
+5 -26
View File
@@ -2,9 +2,9 @@
These functions consolidate the generic data-shaping logic that music services
otherwise each duplicate: first-non-empty getters, duration/year/name
formatting, release-kind classification, track-option dedupe, and Song -> Music
assembly. They take plain data in and return plain data out (no ``self``), so
any music service can reuse them.
formatting, release-kind classification, and Song -> Music assembly. They take
plain data in and return plain data out (no ``self``), so any music service can
reuse them.
"""
from __future__ import annotations
@@ -12,7 +12,6 @@ from __future__ import annotations
import re
from typing import Any, Optional
from unshackle.core.music.models import MusicTrackOption
from unshackle.core.titles.music import Music, Song
@@ -26,7 +25,7 @@ def first_text(*values: Any, default: str = "") -> str:
if value in (None, "", [], {}):
continue
if isinstance(value, dict):
for key in ("name", "title", "display", "display_name", "description", "url"):
for key in ("name", "title", "display", "display_name", "description", "label", "value", "url"):
nested = value.get(key)
text = first_text(nested) if isinstance(nested, (dict, list)) else str(nested or "").strip()
if text:
@@ -111,7 +110,7 @@ def classify_release_kind(raw_kind: str, tracks_count: Optional[float]) -> str:
Returns one of ``single | ep | album | compilation | live | download |
playlist | other``. ``tracks_count`` disambiguates "single" (1 track) from
an EP (more than 1 track) for sources that label EPs as singles; pass the
real track count (or ``None`` only when genuinely unknown) — it is required
real track count (or ``None`` only when genuinely unknown) - it is required
so no caller silently mislabels a multi-track "single" as an EP by omission.
"""
key = re.sub(r"[^a-z0-9]+", "", str(raw_kind or "").lower())
@@ -135,26 +134,6 @@ def classify_release_kind(raw_kind: str, tracks_count: Optional[float]) -> str:
return "album"
def dedupe_track_options(options: list[MusicTrackOption]) -> list[MusicTrackOption]:
"""Drop duplicate track options keyed on codec/quality identity, preserving order."""
seen: set[tuple[str, Optional[int], Optional[int], Optional[int], str, bool]] = set()
unique: list[MusicTrackOption] = []
for option in options:
key = (
str(option.codec or "").upper(),
option.bit_depth,
option.sample_rate,
option.bitrate,
option.quality_label,
option.explicit,
)
if key in seen:
continue
seen.add(key)
unique.append(option)
return unique
def build_music_from_songs(
songs: list[Song],
*,
-16
View File
@@ -1,16 +0,0 @@
from __future__ import annotations
import hashlib
from pathlib import Path
def file_md5(path: Path, chunk_size: int = 1024 * 1024) -> str:
"""Return the MD5 checksum for a local file."""
digest = hashlib.md5()
with path.open("rb") as file:
for chunk in iter(lambda: file.read(chunk_size), b""):
digest.update(chunk)
return digest.hexdigest()
__all__ = ("file_md5",)
-189
View File
@@ -1,189 +0,0 @@
from __future__ import annotations
import subprocess
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Optional
from pymediainfo import MediaInfo
from unshackle.core import binaries
class MusicAudioIntegrityError(Exception):
"""Raised when a downloaded music audio file cannot be trusted."""
@dataclass
class MusicAudioIntegrityResult:
path: Path
size: int
codec: str = ""
duration: Optional[float] = None
bit_depth: Optional[int] = None
sample_rate: Optional[int] = None
channels: Optional[float] = None
flac_tested: bool = False
warnings: list[str] = field(default_factory=list)
def to_dict(self) -> dict[str, Any]:
return {
"path": str(self.path),
"size": self.size,
"codec": self.codec,
"duration": self.duration,
"bit_depth": self.bit_depth,
"sample_rate": self.sample_rate,
"channels": self.channels,
"flac_tested": self.flac_tested,
"warnings": self.warnings,
}
def verify_music_audio(
path: Path, *, song: Any = None, track: Any = None, media_info: Optional[MediaInfo] = None
) -> MusicAudioIntegrityResult:
"""Verify a downloaded music audio file after it is playable/decrypted."""
path = Path(path)
if not path.exists():
raise MusicAudioIntegrityError(f"Audio file is missing: {path}")
size = path.stat().st_size
if size <= 3:
raise MusicAudioIntegrityError(f"Audio file is empty: {path}")
media_info = media_info or MediaInfo.parse(path)
audio_track = next(iter(media_info.audio_tracks or []), None)
if not audio_track:
raise MusicAudioIntegrityError(f"MediaInfo could not find an audio stream in: {path.name}")
duration = duration_seconds(getattr(audio_track, "duration", None))
expected_duration = _expected_duration(song, track)
warnings: list[str] = []
if expected_duration and duration:
tolerance = max(3.0, expected_duration * 0.02)
if abs(duration - expected_duration) > tolerance:
raise MusicAudioIntegrityError(
f"{path.name} duration mismatch: expected {expected_duration:.0f}s, got {duration:.0f}s"
)
result = MusicAudioIntegrityResult(
path=path,
size=size,
codec=first_text(
getattr(audio_track, "format", None),
getattr(audio_track, "commercial_name", None),
getattr(audio_track, "codec_id", None),
),
duration=duration,
bit_depth=first_int(getattr(audio_track, "bit_depth", None)),
sample_rate=first_int(getattr(audio_track, "sampling_rate", None)),
channels=first_float(
getattr(audio_track, "channel_s", None),
getattr(audio_track, "channel_s_original", None),
getattr(track, "channels", None),
),
warnings=warnings,
)
expected_size = _expected_size(track)
if expected_size and result.size != expected_size:
result.warnings.append(f"Size differs from service metadata: expected {expected_size}, got {result.size}")
if path.suffix.lower() == ".flac":
flac = binaries.find("flac")
if flac:
completed = subprocess.run(
[str(flac), "-t", "-s", str(path)],
check=False,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
encoding="utf-8",
errors="replace",
)
if completed.returncode != 0:
detail = (completed.stderr or completed.stdout or "").strip()
raise MusicAudioIntegrityError(f"FLAC stream test failed for {path.name}: {detail}")
result.flac_tested = True
else:
result.warnings.append("flac binary not available; FLAC stream test skipped")
return result
def _expected_duration(song: Any, track: Any) -> Optional[float]:
data = getattr(song, "data", None)
if isinstance(data, dict):
metadata = data.get("metadata") if isinstance(data.get("metadata"), dict) else {}
value = first_float(data.get("duration"), metadata.get("duration"))
if value:
return value
track_data = getattr(track, "data", None)
if isinstance(track_data, dict):
metadata = track_data.get("metadata") if isinstance(track_data.get("metadata"), dict) else {}
value = first_float(track_data.get("duration"), metadata.get("duration"))
if value:
return value
return None
def _expected_size(track: Any) -> Optional[int]:
data = getattr(track, "data", None)
if not isinstance(data, dict):
return None
sources = [
data,
data.get("file_info") if isinstance(data.get("file_info"), dict) else {},
data.get("audio_info") if isinstance(data.get("audio_info"), dict) else {},
data.get("source_info") if isinstance(data.get("source_info"), dict) else {},
data.get("stream_info") if isinstance(data.get("stream_info"), dict) else {},
data.get("metadata") if isinstance(data.get("metadata"), dict) else {},
]
for source in sources:
value = first_int(
source.get("content_length"),
source.get("contentLength"),
source.get("file_size"),
source.get("filesize"),
source.get("size"),
)
if value:
return value
return None
def duration_seconds(value: Any) -> Optional[float]:
number = first_float(value)
if number is None:
return None
if number > 1000:
return number / 1000
return number
def first_text(*values: Any) -> str:
for value in values:
text = str(value or "").strip()
if text:
return text
return ""
def first_float(*values: Any) -> Optional[float]:
for value in values:
if value in (None, "", [], {}):
continue
text = str(value).strip().replace(" ", "")
try:
return float(text)
except (TypeError, ValueError):
continue
return None
def first_int(*values: Any) -> Optional[int]:
value = first_float(*values)
return int(value) if value is not None else None
__all__ = ("MusicAudioIntegrityError", "MusicAudioIntegrityResult", "verify_music_audio")
-23
View File
@@ -1,23 +0,0 @@
from __future__ import annotations
import json
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
def write_music_manifest(path: Path, *, release: dict[str, Any], tracks: list[dict[str, Any]]) -> Path:
"""Write a compact JSON manifest for music integrity, checksums, and metadata results."""
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
payload = {
"schema": "unshackle.music.manifest.v1",
"generated_at": datetime.now(timezone.utc).isoformat(),
"release": release,
"tracks": tracks,
}
path.write_text(json.dumps(payload, indent=2, ensure_ascii=False), encoding="utf-8")
return path
__all__ = ("write_music_manifest",)
-58
View File
@@ -1,58 +0,0 @@
from __future__ import annotations
from dataclasses import dataclass, field
from pathlib import Path
from typing import TYPE_CHECKING, Optional
if TYPE_CHECKING:
from unshackle.core.titles.music import Song
@dataclass
class MusicTrackOption:
codec: str
bit_depth: Optional[int] = None
sample_rate: Optional[int] = None
bitrate: Optional[int] = None
channels: Optional[float] = None
lossless: bool = False
hires: bool = False
atmos: bool = False
explicit: bool = False
duration: Optional[int] = None
quality_label: str = ""
@dataclass
class MusicSongPlan:
song: Song
options: list[MusicTrackOption] = field(default_factory=list)
selected: Optional[MusicTrackOption] = None
output_path: Optional[Path] = None
fallback_used: bool = False
skip_reason: str = ""
@dataclass
class MusicDiscPlan:
disc_number: int
songs: list[MusicSongPlan] = field(default_factory=list)
@dataclass
class MusicDownloadPlan:
kind: str
title: str
artist: str
album_artist: str = ""
year: Optional[int] = None
released: str = ""
genre: str = ""
label: str = ""
artwork_url: Optional[str] = None
total_tracks: Optional[int] = None
total_discs: Optional[int] = None
total_duration: Optional[int] = None
discs: list[MusicDiscPlan] = field(default_factory=list)
quality_requested: str = "best"
fallback_mode: str = "next-best"
-214
View File
@@ -1,214 +0,0 @@
from __future__ import annotations
import re
from collections import defaultdict
from typing import Any
from unshackle.core.music.models import MusicDiscPlan, MusicDownloadPlan, MusicSongPlan, MusicTrackOption
from unshackle.core.titles.music import Music, Song
class MusicPlanner:
"""Build a service-neutral music list/download plan for native Music rendering."""
def __init__(self, service: Any):
self.service = service
def build(self, music: Music) -> MusicDownloadPlan:
first_song = music[0] if music else None
first_data = first_song.data if first_song and isinstance(first_song.data, dict) else {}
first_metadata = first_data.get("metadata") if isinstance(first_data.get("metadata"), dict) else {}
plan = MusicDownloadPlan(
kind=getattr(music, "kind", "music"),
title=getattr(music, "title", None) or (first_song.album if first_song else ""),
artist=getattr(music, "artist", None)
or (first_song.album_artist or first_song.artist if first_song else ""),
album_artist=(first_song.album_artist if first_song else "") or "",
year=getattr(music, "year", None) or (first_song.year if first_song else None),
released=self.first_text(
getattr(music, "released", None),
getattr(music, "release_date", None),
first_data.get("release_date"),
first_data.get("released_at"),
first_metadata.get("release_date"),
first_metadata.get("released_at"),
),
genre=(first_song.genre if first_song else "") or "",
label=(first_song.label if first_song else "") or "",
artwork_url=getattr(music, "artwork_url", None),
total_tracks=getattr(music, "total_tracks", None) or len(music),
total_discs=getattr(music, "total_discs", None) or self.max_value(music, "disc"),
total_duration=getattr(music, "total_duration", None) or self.sum_duration(music),
quality_requested=self.quality_requested(music),
)
selected_options: list[MusicTrackOption] = []
discs: dict[int, list[MusicSongPlan]] = defaultdict(list)
for song in music:
options = self.get_options(song)
selected = options[0] if options else None
if selected:
selected_options.append(selected)
discs[song.disc].append(
MusicSongPlan(
song=song,
options=options,
selected=selected,
)
)
for disc_number in sorted(discs):
plan.discs.append(MusicDiscPlan(disc_number=disc_number, songs=discs[disc_number]))
quality = self.quality_summary_from_options(selected_options)
if quality:
plan.quality_requested = quality
return plan
def get_options(self, song: Song) -> list[MusicTrackOption]:
provider = getattr(self.service, "get_music_track_options", None)
if callable(provider):
options = provider(song)
if options:
return options
option = self.option_from_song(song)
return [option] if option else []
@staticmethod
def option_from_song(song: Song) -> MusicTrackOption | None:
data = song.data if isinstance(song.data, dict) else {}
metadata = data.get("metadata") if isinstance(data.get("metadata"), dict) else {}
quality = MusicPlanner.first_text(data.get("quality"), metadata.get("quality"), metadata.get("quality_label"))
duration = MusicPlanner.first_number(data.get("duration"), metadata.get("duration"))
if not quality and duration is None:
return None
codec = MusicPlanner.codec_from_quality(quality)
bit_depth, sample_rate = MusicPlanner.quality_numbers(quality)
bitrate = MusicPlanner.bitrate_from_quality(quality)
hires = bool((bit_depth and bit_depth > 16) or (sample_rate and sample_rate > 48000))
lossless = codec in {"FLAC", "ALAC", "WAV", "AIFF"} or "lossless" in quality.lower()
atmos = "atmos" in quality.lower() or bool(data.get("atmos") or metadata.get("atmos"))
explicit = bool(getattr(song, "explicit", None) or data.get("explicit") or metadata.get("explicit"))
return MusicTrackOption(
codec=codec,
bit_depth=bit_depth,
sample_rate=sample_rate,
bitrate=bitrate,
channels=MusicPlanner.first_number(data.get("channels"), metadata.get("channels")),
lossless=lossless,
hires=hires,
atmos=atmos,
explicit=explicit,
duration=int(duration) if duration is not None else None,
quality_label=quality,
)
def quality_requested(self, music: Music) -> str:
service_quality = getattr(self.service, "quality", None)
if service_quality:
quality_map = {
27: "Hi-Res Lossless",
7: "Hi-Res Lossless",
6: "Lossless",
5: "MP3",
}
return quality_map.get(service_quality, str(service_quality))
first_song = music[0] if music else None
if not first_song:
return ""
data = first_song.data if isinstance(first_song.data, dict) else {}
return self.first_text(data.get("quality"))
@staticmethod
def first_text(*values: Any) -> str:
for value in values:
if value in (None, ""):
continue
text = str(value).strip()
if text:
return text
return ""
@staticmethod
def first_number(*values: Any) -> float | None:
for value in values:
if value in (None, ""):
continue
try:
return float(value)
except (TypeError, ValueError):
continue
return None
@staticmethod
def codec_from_quality(value: str) -> str:
lowered = value.lower()
for codec in ("flac", "alac", "aac", "mp3", "wav", "aiff"):
if codec in lowered:
return codec.upper()
return ""
@staticmethod
def quality_numbers(value: str) -> tuple[int | None, int | None]:
bit_depth = None
sample_rate = None
bit_match = re.search(r"(?P<bits>\d+)\s*[- ]?bit", value.lower())
if bit_match:
bit_depth = int(bit_match.group("bits"))
sample_match = re.search(r"(?P<rate>\d+(?:\.\d+)?)\s*k(?:hz)?", value.lower())
if sample_match:
sample_rate = int(float(sample_match.group("rate")) * 1000)
return bit_depth, sample_rate
@staticmethod
def bitrate_from_quality(value: str) -> int | None:
match = re.search(r"(?P<rate>\d+)\s*kb/s", value.lower())
if not match:
return None
return int(match.group("rate")) * 1000
@staticmethod
def quality_summary_from_options(options: list[MusicTrackOption]) -> str:
if not options:
return ""
codecs = {str(option.codec or "").upper() for option in options if option.codec}
labels = [option.quality_label for option in options if option.quality_label]
if any(option.atmos for option in options):
return "Dolby Atmos"
if any(
option.hires and (option.lossless or str(option.codec or "").upper() in {"FLAC", "ALAC", "WAV", "AIFF"})
for option in options
):
return "Hi-Res Lossless"
if any(
option.lossless or str(option.codec or "").upper() in {"FLAC", "ALAC", "WAV", "AIFF"} for option in options
):
return "Lossless"
if "AAC" in codecs:
return "AAC"
if "MP3" in codecs:
return "MP3"
return MusicPlanner.first_text(*labels)
@staticmethod
def sum_duration(music: Music) -> int | None:
total = 0
for song in music:
data = song.data if isinstance(song.data, dict) else {}
value = MusicPlanner.first_number(data.get("duration"))
total += int(value or 0)
return total or None
@staticmethod
def max_value(music: Music, attr: str) -> int | None:
values = [getattr(song, attr, 0) or 0 for song in music]
return max(values, default=0) or None
__all__ = ("MusicPlanner",)
+39 -227
View File
@@ -3,33 +3,28 @@ from __future__ import annotations
import re
from typing import Any, Optional
from rich import box
from rich.console import Group, RenderableType
from rich.markup import escape
from rich.panel import Panel
from rich.table import Table
from rich.text import Text
from rich.tree import Tree
from unshackle.core.music.models import MusicDownloadPlan, MusicTrackOption
from unshackle.core.console import listing_panel
from unshackle.core.music.extract import first_text, format_duration
from unshackle.core.titles.music import Music, Song
class MusicRenderer:
"""Render native Music title containers for the CLI."""
"""Render a Music release for the CLI title listing.
COMPACT_TRACK_LIMIT = 8
The album header and per-track lines are specific to music. The box around
the tracklist comes from ``listing_panel``, so it restyles along with the
track listing that core prints for every other title type.
"""
def render(self, music: Music, *, verbose: bool = False) -> RenderableType:
def render(self, music: Music) -> RenderableType:
header = self.render_header(music)
tracks = self.render_tracks(music, verbose=verbose)
if header:
return Group(header, Text(""), tracks)
return tracks
def render_plan(self, plan: MusicDownloadPlan, *, verbose: bool = True) -> RenderableType:
header = self.render_plan_header(plan)
tracks = self.render_plan_tracks(plan, verbose=verbose)
tracks = self.render_tracks(music)
if header:
return Group(header, Text(""), tracks)
return tracks
@@ -60,7 +55,7 @@ class MusicRenderer:
)
length = self.format_total_duration(getattr(music, "total_duration", None) or self.sum_duration(music))
quality = self.quality_summary(
self.first_text(
first_text(
getattr(music, "quality", None),
data.get("quality"),
metadata.get("quality"),
@@ -70,119 +65,44 @@ class MusicRenderer:
hires=self.as_bool(self.first_value(data.get("hires"), metadata.get("hires"))),
)
grid = self.metadata_grid()
grid = Table.grid(padding=(0, 2))
grid.add_column(style="bright_black", no_wrap=True)
grid.add_column()
grid.add_row(Text("Title", style="bright_black"), Text(str(title)))
grid.add_row(Text("Artist", style="bright_black"), Text(str(artist)))
grid.add_row(Text("Type", style="bright_black"), self.kind_text(kind, explicit=explicit))
# values are service data, so they stay Text and never get parsed as markup
grid.add_row("Title", Text(str(title)))
grid.add_row("Artist", Text(str(artist)))
grid.add_row("Type", self.kind_text(kind, explicit=explicit))
if released:
grid.add_row(Text("Released", style="bright_black"), Text(released))
grid.add_row("Released", Text(released))
if year:
grid.add_row(Text("Year", style="bright_black"), Text(str(year)))
grid.add_row(Text("Tracks", style="bright_black"), Text(str(total_tracks)))
grid.add_row("Year", Text(str(year)))
grid.add_row("Tracks", Text(str(total_tracks)))
if total_discs and total_discs > 1:
grid.add_row(Text("Discs", style="bright_black"), Text(str(total_discs)))
grid.add_row("Discs", Text(str(total_discs)))
if length:
grid.add_row(Text("Length", style="bright_black"), Text(length))
grid.add_row("Length", Text(length))
if quality:
grid.add_row(Text("Quality", style="bright_black"), Text(quality))
grid.add_row("Quality", Text(quality))
if first_song.genre:
grid.add_row(Text("Genre", style="bright_black"), Text(first_song.genre))
grid.add_row("Genre", Text(first_song.genre))
if first_song.label:
grid.add_row(Text("Label", style="bright_black"), Text(first_song.label))
grid.add_row("Label", Text(first_song.label))
return grid
def render_tracks(self, music: Music, *, verbose: bool = False) -> Panel:
def render_tracks(self, music: Music) -> Panel:
total = len(music)
track_label = "Track" if total == 1 else "Tracks"
tree = Tree(f"[repr.number]{total}[/] {track_label}", guide_style="bright_black")
visible_songs = list(music)
if not verbose and len(visible_songs) > self.COMPACT_TRACK_LIMIT:
visible_songs = visible_songs[: self.COMPACT_TRACK_LIMIT]
for song in visible_songs:
node = tree.add(self.song_line(song, music), guide_style="bright_black")
for song in music:
node = tree.add(self.song_line(song, music))
option = self.option_from_song(song)
if option:
node.add(option, guide_style="bright_black")
node.add(option)
hidden = total - len(visible_songs)
if hidden > 0:
suffix = "s" if hidden != 1 else ""
tree.add(f"[bright_black]... {hidden} more track{suffix}[/]", guide_style="bright_black")
return Panel(tree, title="Available Tracks", box=box.SQUARE, border_style="bright_black")
def render_plan_header(self, plan: MusicDownloadPlan) -> Optional[Table]:
title = plan.title
artist = plan.artist or plan.album_artist
kind = self.display_kind(plan.kind)
explicit = any(
bool(getattr(song_plan.song, "explicit", None) or (song_plan.selected and song_plan.selected.explicit))
for disc in plan.discs
for song_plan in disc.songs
)
released = self.format_release_date(getattr(plan, "released", None) or getattr(plan, "release_date", None))
length = self.format_total_duration(plan.total_duration)
quality = self.quality_summary(plan.quality_requested)
grid = self.metadata_grid()
if title:
grid.add_row(Text("Title", style="bright_black"), Text(str(title)))
if artist:
grid.add_row(Text("Artist", style="bright_black"), Text(str(artist)))
grid.add_row(Text("Type", style="bright_black"), self.kind_text(kind, explicit=explicit))
if released:
grid.add_row(Text("Released", style="bright_black"), Text(released))
if plan.year:
grid.add_row(Text("Year", style="bright_black"), Text(str(plan.year)))
if plan.total_tracks:
grid.add_row(Text("Tracks", style="bright_black"), Text(str(plan.total_tracks)))
if plan.total_discs and plan.total_discs > 1:
grid.add_row(Text("Discs", style="bright_black"), Text(str(plan.total_discs)))
if length:
grid.add_row(Text("Length", style="bright_black"), Text(length))
if quality:
grid.add_row(Text("Quality", style="bright_black"), Text(quality))
if plan.genre:
grid.add_row(Text("Genre", style="bright_black"), Text(str(plan.genre)))
if plan.label:
grid.add_row(Text("Label", style="bright_black"), Text(str(plan.label)))
return grid
def render_plan_tracks(self, plan: MusicDownloadPlan, *, verbose: bool = True) -> Panel:
songs = [song_plan for disc in plan.discs for song_plan in disc.songs]
total = len(songs)
track_label = "Track" if total == 1 else "Tracks"
tree = Tree(f"[repr.number]{total}[/] {track_label}", guide_style="bright_black")
visible_songs = songs
if not verbose and len(visible_songs) > self.COMPACT_TRACK_LIMIT:
visible_songs = visible_songs[: self.COMPACT_TRACK_LIMIT]
for song_plan in visible_songs:
node = tree.add(self.song_line(song_plan.song, plan), guide_style="bright_black")
if song_plan.skip_reason:
node.add(f"[yellow]Skipped:[/] {escape(song_plan.skip_reason)}", guide_style="bright_black")
continue
for option in song_plan.options:
node.add(self.option_line(option), guide_style="bright_black")
hidden = total - len(visible_songs)
if hidden > 0:
suffix = "s" if hidden != 1 else ""
tree.add(f"[bright_black]... {hidden} more track{suffix}[/]", guide_style="bright_black")
return Panel(tree, title="Available Tracks", box=box.SQUARE, border_style="bright_black")
@staticmethod
def metadata_grid() -> Table:
grid = Table.grid(padding=(0, 2))
grid.add_column(style="orchid1", no_wrap=True)
grid.add_column()
return grid
return listing_panel(tree, "Tracklist")
@staticmethod
def display_kind(kind: Any) -> str:
@@ -205,7 +125,7 @@ class MusicRenderer:
return labels[key]
return text.replace("_", " ").replace("-", " ").title()
def song_line(self, song: Song, music: Music | MusicDownloadPlan) -> Text:
def song_line(self, song: Song, music: Music) -> Text:
number = f"{song.disc}.{song.track:02}" if song.disc > 1 else f"{song.track:02}"
line = Text()
line.append(number, style="repr.number")
@@ -217,20 +137,22 @@ class MusicRenderer:
line.append(f" - {song.artist}", style="bright_black")
return line
def option_from_song(self, song: Song) -> Text | str:
def option_from_song(self, song: Song) -> Text:
data = song.data if isinstance(song.data, dict) else {}
metadata = data.get("metadata") if isinstance(data.get("metadata"), dict) else {}
quality = self.first_text(data.get("quality"), metadata.get("quality"), metadata.get("quality_label"))
duration = self.format_duration(self.first_value(data.get("duration"), metadata.get("duration")))
reason = self.first_text(
quality = first_text(data.get("quality"), metadata.get("quality"), metadata.get("quality_label"))
raw_duration = self.first_value(data.get("duration"), metadata.get("duration"))
# an already-formatted duration ("3:45") does not parse as seconds, so show it as given
duration = format_duration(raw_duration) or first_text(raw_duration)
reason = first_text(
data.get("unavailable_reason"),
data.get("skip_reason"),
metadata.get("unavailable_reason"),
metadata.get("skip_reason"),
)
if reason:
return f"[yellow]Skipped:[/] {escape(reason)}"
return Text.assemble(("Skipped:", "yellow"), f" {reason}")
badges = []
if song.explicit:
@@ -246,35 +168,9 @@ class MusicRenderer:
if duration:
details.append(duration)
if not details and not badges:
return ""
return Text()
return self.format_option_text(details, badges)
def option_line(self, option: MusicTrackOption) -> Text:
parts = []
codec = str(option.codec or "").strip()
if codec:
parts.append(f"[{codec}]")
if option.quality_label:
parts.extend(self.split_quality_label(option.quality_label, codec))
elif option.bit_depth and option.sample_rate:
parts.append(f"{option.bit_depth}-bit/{self.format_sample_rate(option.sample_rate)}")
elif option.bitrate:
parts.append(f"{int(option.bitrate / 1000)} kb/s")
if option.channels:
parts.append(self.format_channels(option.channels))
if option.duration:
parts.append(self.format_duration(option.duration))
badges = []
if option.explicit:
badges.append(("E", "bold bright_red"))
if option.atmos:
badges.append(("Atmos", "magenta"))
if self.is_cd_option(option):
badges.append(("CD", "yellow1"))
if option.hires:
badges.append(("Hi-Res", "gold1"))
return self.format_option_text(parts, badges)
@staticmethod
def kind_text(kind: str, *, explicit: bool = False) -> Text:
text = Text(str(kind))
@@ -300,76 +196,6 @@ class MusicRenderer:
first = False
return text
@staticmethod
def format_option_parts(parts: list[str]) -> str:
if not parts:
return ""
return " | ".join(escape(part) for part in parts if part)
@staticmethod
def split_quality_label(value: str, codec: str = "") -> list[str]:
text = str(value or "").strip()
if not text:
return []
if codec and text.lower().startswith(codec.lower()):
text = text[len(codec) :].strip()
return [text] if text else []
@staticmethod
def is_cd_option(option: MusicTrackOption) -> bool:
codec = str(option.codec or "").upper()
if codec not in {"FLAC", "ALAC", "WAV", "AIFF"}:
return False
if option.bit_depth == 16 and option.sample_rate in {44100, 44100.0}:
return True
return "16-bit/44.1" in str(option.quality_label or "").lower()
@staticmethod
def format_sample_rate(value: Any) -> str:
try:
sample_rate = float(value)
except (TypeError, ValueError):
return str(value).strip()
if sample_rate >= 1000:
sample_rate /= 1000
if sample_rate.is_integer():
return f"{int(sample_rate)} kHz"
return f"{sample_rate:g} kHz"
@staticmethod
def format_channels(value: Any) -> str:
try:
channels = float(value)
except (TypeError, ValueError):
return str(value).strip()
if channels == 1:
return "Mono"
if channels == 2:
return "Stereo"
if channels.is_integer():
return f"{int(channels)}.0"
return f"{channels:g}"
@staticmethod
def first_text(*values: Any) -> str:
for value in values:
if value is None:
continue
if isinstance(value, dict):
for key in ("label", "name", "title", "display_name", "value"):
nested = value.get(key)
if nested:
return str(nested).strip()
elif isinstance(value, (list, tuple)):
text = MusicRenderer.first_text(*value)
if text:
return text
else:
text = str(value).strip()
if text:
return text
return ""
@staticmethod
def first_value(*values: Any) -> Any:
for value in values:
@@ -385,20 +211,6 @@ class MusicRenderer:
return value.strip().lower() in {"1", "true", "yes", "y"}
return bool(value)
@staticmethod
def format_duration(value: Any) -> str:
if value in (None, ""):
return ""
try:
seconds = int(float(value))
except (TypeError, ValueError):
return str(value).strip()
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
if hours:
return f"{hours}:{minutes:02}:{seconds:02}"
return f"{minutes}:{seconds:02}"
@staticmethod
def format_total_duration(value: Any) -> str:
if value in (None, ""):
+56 -18
View File
@@ -1,6 +1,7 @@
from __future__ import annotations
import logging
from base64 import b64encode
from dataclasses import dataclass
from io import BytesIO
from pathlib import Path
@@ -30,15 +31,18 @@ try:
TRCK,
TSRC,
TXXX,
USLT,
ID3NoHeaderError,
)
from mutagen.mp3 import MP3
from mutagen.mp4 import MP4, MP4Cover
from mutagen.oggvorbis import OggVorbis
except ImportError: # pragma: no cover - optional tagging dependency
FLAC = Picture = None
MP3 = MP4 = MP4Cover = None
MP3 = MP4 = MP4Cover = OggVorbis = None
ID3NoHeaderError = Exception
APIC = COMM = TALB = TCOM = TCON = TCOP = TDRC = TIT2 = TPE1 = TPE2 = TPOS = TRCK = TSRC = TXXX = None
USLT = None
log = logging.getLogger("MUSIC_TAGGER")
@@ -61,10 +65,10 @@ class MusicMetadataResult:
def write_music_metadata(path: Path, song: Any, *, session: Any = None, source_md5: str = "") -> MusicMetadataResult:
"""Write normalized music metadata for FLAC, MP3, and M4A/MP4 audio files."""
"""Write normalized music metadata for FLAC, Ogg, MP3, and M4A/MP4 audio files."""
path = Path(path)
extension = path.suffix.lower()
if extension not in {".flac", ".mp3", ".m4a", ".mp4"}:
if extension not in {".flac", ".mp3", ".m4a", ".mp4", ".ogg"}:
return MusicMetadataResult(skipped=True, reason=f"Unsupported music metadata container: {extension}")
if extension == ".flac" and FLAC is None:
@@ -73,6 +77,8 @@ def write_music_metadata(path: Path, song: Any, *, session: Any = None, source_m
return MusicMetadataResult(skipped=True, reason="install mutagen to write MP3 tags")
if extension in {".m4a", ".mp4"} and MP4 is None:
return MusicMetadataResult(skipped=True, reason="install mutagen to write MP4/M4A tags")
if extension == ".ogg" and OggVorbis is None:
return MusicMetadataResult(skipped=True, reason="install mutagen to write Ogg tags")
tags = build_tag_values(song, source_md5=source_md5)
artwork_url = first_text(getattr(song, "artwork_url", None), _metadata(song).get("artwork_url"))
@@ -80,6 +86,8 @@ def write_music_metadata(path: Path, song: Any, *, session: Any = None, source_m
if extension == ".flac":
write_flac_tags(path, tags, cover_data, mime_type)
elif extension == ".ogg":
write_ogg_tags(path, tags, cover_data, mime_type)
elif extension == ".mp3":
write_mp3_tags(path, tags, cover_data, mime_type)
else:
@@ -116,6 +124,7 @@ def build_tag_values(song: Any, *, source_md5: str = "") -> dict[str, str]:
"COPYRIGHT": string_tag(getattr(song, "copyright", None) or metadata.get("copyright")),
"LABEL": first_text(getattr(song, "label", None), metadata.get("label")),
"COMMENT": first_text(metadata.get("comment"), metadata.get("quality")),
"LYRICS": first_text(getattr(song, "lyrics", None), metadata.get("lyrics")),
"SOURCE": first_text(metadata.get("source"), metadata.get("service")),
"ENCODEDBY": "Unshackle",
"UNSHACKLE_SOURCE_MD5": source_md5,
@@ -145,24 +154,43 @@ def write_flac_tags(path: Path, tags: dict[str, str], cover_data: Optional[bytes
audio = FLAC(path)
for key, value in tags.items():
audio[key] = [value]
if cover_data and Picture is not None:
picture = Picture()
picture.type = 3
picture.mime = mime_type or "image/jpeg"
picture.desc = "Cover"
picture.data = cover_data
if Image is not None:
try:
with Image.open(BytesIO(cover_data)) as image:
picture.width, picture.height = image.size
picture.depth = len(image.getbands()) * 8
except Exception:
pass
picture = build_picture(cover_data, mime_type)
if picture is not None:
audio.clear_pictures()
audio.add_picture(picture)
audio.save()
def build_picture(cover_data: Optional[bytes], mime_type: str) -> Optional[Any]:
"""Build a FLAC Picture block, which Ogg reuses base64-encoded."""
if not cover_data or Picture is None:
return None
picture = Picture()
picture.type = 3
picture.mime = mime_type or "image/jpeg"
picture.desc = "Cover"
picture.data = cover_data
if Image is not None:
try:
with Image.open(BytesIO(cover_data)) as image:
picture.width, picture.height = image.size
picture.depth = len(image.getbands()) * 8
except Exception:
pass
return picture
def write_ogg_tags(path: Path, tags: dict[str, str], cover_data: Optional[bytes], mime_type: str) -> None:
audio = OggVorbis(path)
for key, value in tags.items():
audio[key] = [value]
picture = build_picture(cover_data, mime_type)
if picture is not None:
# Ogg carries no picture block of its own, so the FLAC block goes in base64
audio["METADATA_BLOCK_PICTURE"] = [b64encode(picture.write()).decode("ascii")]
audio.save()
def write_mp3_tags(path: Path, tags: dict[str, str], cover_data: Optional[bytes], mime_type: str) -> None:
try:
audio = MP3(path)
@@ -191,11 +219,13 @@ def write_mp3_tags(path: Path, tags: dict[str, str], cover_data: Optional[bytes]
audio.tags.setall(frame_id, [frame_class(encoding=3, text=[value])])
if tags.get("COMMENT") and COMM is not None:
audio.tags.setall("COMM", [COMM(encoding=3, lang="eng", desc="", text=[tags["COMMENT"]])])
if tags.get("LYRICS") and USLT is not None:
audio.tags.setall("USLT", [USLT(encoding=3, lang="eng", desc="", text=tags["LYRICS"])])
if cover_data and APIC is not None:
audio.tags.delall("APIC")
audio.tags.add(APIC(encoding=3, mime=mime_type or "image/jpeg", type=3, desc="Cover", data=cover_data))
custom_keys = set(tags) - set(frame_map) - {"COMMENT"}
custom_keys = set(tags) - set(frame_map) - {"COMMENT", "LYRICS"}
for key in sorted(custom_keys):
if TXXX is not None and tags[key]:
audio.tags.delall(f"TXXX:{key}")
@@ -223,6 +253,8 @@ def write_mp4_tags(path: Path, tags: dict[str, str], cover_data: Optional[bytes]
audio["\xa9cmt"] = [tags["COMMENT"]]
if tags.get("COPYRIGHT"):
audio["cprt"] = [tags["COPYRIGHT"]]
if tags.get("LYRICS"):
audio["\xa9lyr"] = [tags["LYRICS"]]
track_number, track_total = split_number_pair(tags.get("TRACKNUMBER", ""))
if track_number:
@@ -244,6 +276,7 @@ def write_mp4_tags(path: Path, tags: dict[str, str], cover_data: Optional[bytes]
"COMPOSER",
"COMMENT",
"COPYRIGHT",
"LYRICS",
"TRACKNUMBER",
"DISCNUMBER",
}
@@ -272,7 +305,12 @@ def download_cover(session: Any, artwork_url: str) -> tuple[Optional[bytes], str
def _metadata(song: Any) -> dict[str, Any]:
data = getattr(song, "data", None)
return data if isinstance(data, dict) else {}
if not isinstance(data, dict):
return {}
# the renderer reads a nested "metadata" sub-dict as well as the top level, so a
# service that follows it would otherwise lose every tag read through this helper
nested = data.get("metadata")
return {**data, **nested} if isinstance(nested, dict) else data
def first_text(*values: Any) -> str: