mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-27 11:25:08 +00:00
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:
@@ -328,7 +328,8 @@ def perform_download(
|
||||
`params` holds the API's string form of the `dl` options and is normalized in place before
|
||||
dl.result() sees it: vcodec and range names become enums, `slow` accepts "MIN-MAX", a two-item
|
||||
list, or True (which means 60-120), and `wanted` accepts forms such as "S01E01", "S01-S03",
|
||||
"s1e1", or "1x1" as well as the internal "SxE" form.
|
||||
"s1e1", or "1x1" as well as the internal "SxE" form. Music takes track numbers in the same
|
||||
field, such as "1-5" or "2x3" for disc 2 track 3.
|
||||
"""
|
||||
|
||||
from contextlib import redirect_stderr, redirect_stdout
|
||||
@@ -408,7 +409,8 @@ def perform_download(
|
||||
from unshackle.core.utils.click_types import SeasonRange
|
||||
|
||||
if isinstance(wanted_raw, str):
|
||||
wanted_raw = [wanted_raw]
|
||||
# the CLI splits a comma-separated value before parsing, so a raw string must too
|
||||
wanted_raw = re.split(r"\s*[,;]\s*", wanted_raw)
|
||||
# the !? keeps a pre-parsed part exclusion from being re-fed through parse_tokens
|
||||
needs_conversion = any(not re.match(r"^!?\d+x\d+(\.\d+)?$", w) for w in wanted_raw)
|
||||
if needs_conversion:
|
||||
|
||||
@@ -18,7 +18,7 @@ from unshackle.core.constants import AUDIO_CODEC_MAP, DYNAMIC_RANGE_MAP, VIDEO_C
|
||||
from unshackle.core.providers.anilist import parse_anilist_ref
|
||||
from unshackle.core.proxies.resolve import initialize_proxy_providers, resolve_proxy
|
||||
from unshackle.core.services import Services
|
||||
from unshackle.core.titles import Episode, Movie, Title_T
|
||||
from unshackle.core.titles import Episode, Movie, Song, Title_T
|
||||
from unshackle.core.tracks import Audio, Subtitle, Tracks, Video
|
||||
from unshackle.core.utils.collections import ci_get
|
||||
from unshackle.core.utils.redact import REDACTED, URL_USERINFO_RE
|
||||
@@ -791,7 +791,9 @@ async def list_tracks_handler(data: Dict[str, Any], request: Optional[web.Reques
|
||||
if isinstance(wanted_param, list):
|
||||
wanted = season_range.parse_tokens(*wanted_param)
|
||||
else:
|
||||
wanted = season_range.parse_tokens(wanted_param)
|
||||
# convert(), not parse_tokens(), so a comma-separated string splits
|
||||
# into tokens the way the CLI splits it
|
||||
wanted = season_range.convert(wanted_param)
|
||||
log.debug(
|
||||
f"Parsed wanted '{sanitize_log(wanted_param)}' into {len(wanted)} episodes: {wanted[:10]}..."
|
||||
)
|
||||
@@ -806,7 +808,7 @@ async def list_tracks_handler(data: Dict[str, Any], request: Optional[web.Reques
|
||||
|
||||
if wanted:
|
||||
# Filter titles based on wanted episodes, similar to how dl.py does it
|
||||
matching_titles = []
|
||||
matching_titles: list[Any] = []
|
||||
log.debug(f"Filtering {len(titles_list)} titles with {len(wanted)} wanted episodes")
|
||||
for title in titles_list:
|
||||
if isinstance(title, Episode):
|
||||
@@ -816,6 +818,13 @@ async def list_tracks_handler(data: Dict[str, Any], request: Optional[web.Reques
|
||||
matching_titles.append(title)
|
||||
else:
|
||||
log.debug(f"Episode {episode_key} not in wanted list")
|
||||
elif isinstance(title, Song):
|
||||
song_key = f"{title.disc}x{title.track}"
|
||||
if title.matches_wanted(wanted):
|
||||
log.debug(f"Song {song_key} matches wanted list")
|
||||
matching_titles.append(title)
|
||||
else:
|
||||
log.debug(f"Song {song_key} not in wanted list")
|
||||
else:
|
||||
matching_titles.append(title)
|
||||
|
||||
@@ -824,7 +833,7 @@ async def list_tracks_handler(data: Dict[str, Any], request: Optional[web.Reques
|
||||
if not matching_titles:
|
||||
raise APIError(
|
||||
APIErrorCode.NO_CONTENT,
|
||||
"No episodes found matching wanted criteria",
|
||||
"No titles found matching wanted criteria",
|
||||
details={
|
||||
"service": normalized_service,
|
||||
"title_id": title_id,
|
||||
|
||||
@@ -563,7 +563,7 @@ async def list_tracks(request: web.Request) -> web.Response:
|
||||
description: Title identifier
|
||||
wanted:
|
||||
type: string
|
||||
description: Specific episode/season (optional)
|
||||
description: Specific episode/season, or music track ("1-5", "2x3" for disc 2 track 3) (optional)
|
||||
proxy:
|
||||
type: string
|
||||
description: Proxy configuration (optional)
|
||||
@@ -657,7 +657,7 @@ async def download(request: web.Request) -> web.Response:
|
||||
type: array
|
||||
items:
|
||||
type: string
|
||||
description: Wanted episodes (e.g., ["S01E01", "S01E02"]) (default - all)
|
||||
description: Wanted episodes (e.g., ["S01E01", "S01E02"]) or music tracks (e.g., ["1-5"], ["2x3"] for disc 2 track 3) (default - all)
|
||||
latest_episode:
|
||||
type: boolean
|
||||
description: Download only the single most recent episode (default - false)
|
||||
|
||||
@@ -268,7 +268,7 @@ class Config:
|
||||
Args:
|
||||
template_type: One of "movies", "series", or "songs".
|
||||
"""
|
||||
template = self.output_template[template_type]
|
||||
template = self.output_template.get(template_type) or ""
|
||||
between_vars = re.findall(r"\}([^{]*)\{", template)
|
||||
separator_text = "".join(between_vars)
|
||||
dot_count = separator_text.count(".")
|
||||
|
||||
@@ -4,6 +4,7 @@ from datetime import datetime
|
||||
from types import ModuleType
|
||||
from typing import IO, Any, Callable, Iterable, List, Literal, Mapping, Optional, TextIO, Union
|
||||
|
||||
from rich import box
|
||||
from rich._log_render import FormatTimeCallable, LogRender
|
||||
from rich.color import Color, blend_rgb
|
||||
from rich.console import Console, ConsoleOptions, ConsoleRenderable, HighlighterType, RenderableType, RenderResult
|
||||
@@ -13,6 +14,7 @@ from rich.live import Live
|
||||
from rich.logging import RichHandler
|
||||
from rich.measure import Measurement
|
||||
from rich.padding import Padding, PaddingDimensions
|
||||
from rich.panel import Panel
|
||||
from rich.progress import BarColumn, Task
|
||||
from rich.status import Status
|
||||
from rich.style import Style, StyleType
|
||||
@@ -427,6 +429,11 @@ console = ComfyConsole(
|
||||
)
|
||||
|
||||
|
||||
def listing_panel(renderable: RenderableType, title: str) -> Panel:
|
||||
"""Box a listing in the shared panel style, so every listing restyles from one place."""
|
||||
return Panel(renderable, title=title, box=box.SQUARE, border_style="bright_black")
|
||||
|
||||
|
||||
def prompt_user(prompt: str) -> str:
|
||||
"""Ask the user for input on the shared console, themed and indented like the rest of the output."""
|
||||
indent = " " * 5
|
||||
@@ -442,5 +449,6 @@ __all__ = (
|
||||
"GradientPulseBarColumn",
|
||||
"SyncLive",
|
||||
"console",
|
||||
"listing_panel",
|
||||
"prompt_user",
|
||||
)
|
||||
|
||||
@@ -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",
|
||||
)
|
||||
|
||||
@@ -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
|
||||
@@ -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],
|
||||
*,
|
||||
|
||||
@@ -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",)
|
||||
@@ -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")
|
||||
@@ -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",)
|
||||
@@ -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"
|
||||
@@ -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",)
|
||||
@@ -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, ""):
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -6,6 +6,7 @@ from typing import Any, Collection, Iterable, Optional, Union
|
||||
|
||||
from langcodes import Language
|
||||
from pymediainfo import MediaInfo
|
||||
from rich.console import RenderableType
|
||||
from rich.tree import Tree
|
||||
from sortedcontainers import SortedKeyList
|
||||
|
||||
@@ -272,7 +273,7 @@ class Series(SortedKeyList, ABC):
|
||||
return super().__str__()
|
||||
return self[0].title + (f" ({self[0].year})" if self[0].year else "")
|
||||
|
||||
def tree(self, verbose: bool = False) -> Tree:
|
||||
def tree(self, verbose: bool = False) -> RenderableType:
|
||||
seasons = Counter(x.season for x in self)
|
||||
num_seasons = len(seasons)
|
||||
sum(seasons.values())
|
||||
|
||||
@@ -4,6 +4,7 @@ from typing import Any, Iterable, Optional, Union
|
||||
|
||||
from langcodes import Language
|
||||
from pymediainfo import MediaInfo
|
||||
from rich.console import RenderableType
|
||||
from rich.tree import Tree
|
||||
from sortedcontainers import SortedKeyList
|
||||
|
||||
@@ -90,7 +91,7 @@ class Movies(SortedKeyList, ABC):
|
||||
# TODO: Assumes there's only one movie
|
||||
return self[0].name + (f" ({self[0].year})" if self[0].year else "")
|
||||
|
||||
def tree(self, verbose: bool = False) -> Tree:
|
||||
def tree(self, verbose: bool = False) -> RenderableType:
|
||||
num_movies = len(self)
|
||||
tree = Tree(f"{num_movies} Movie{['s', ''][num_movies == 1]}", guide_style="bright_black")
|
||||
if verbose:
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import re
|
||||
from abc import ABC
|
||||
from typing import Any, Iterable, Optional, Union
|
||||
from typing import Any, Collection, Iterable, Optional, Union
|
||||
|
||||
from langcodes import Language
|
||||
from pymediainfo import MediaInfo
|
||||
from rich.console import RenderableType
|
||||
from sortedcontainers import SortedKeyList
|
||||
|
||||
from unshackle.core.config import config
|
||||
@@ -21,8 +22,8 @@ class Song(Title):
|
||||
artist: str,
|
||||
album: str,
|
||||
track: int,
|
||||
disc: int,
|
||||
year: int,
|
||||
disc: int = 1,
|
||||
year: Optional[int] = None,
|
||||
language: Optional[Union[str, Language]] = None,
|
||||
data: Optional[Any] = None,
|
||||
album_artist: Optional[str] = None,
|
||||
@@ -60,14 +61,10 @@ class Song(Title):
|
||||
if not isinstance(track, int):
|
||||
raise TypeError(f"Expected track to be an int, not {track!r}")
|
||||
|
||||
if not disc:
|
||||
raise ValueError("Song disc must be provided")
|
||||
if not isinstance(disc, int):
|
||||
raise TypeError(f"Expected disc to be an int, not {disc!r}")
|
||||
|
||||
if not year:
|
||||
raise ValueError("Song year must be provided")
|
||||
if not isinstance(year, int):
|
||||
if year is not None and not isinstance(year, int):
|
||||
raise TypeError(f"Expected year to be an int, not {year!r}")
|
||||
if album_artist is not None and not isinstance(album_artist, str):
|
||||
raise TypeError(f"Expected album_artist to be a str, not {album_artist!r}")
|
||||
@@ -111,7 +108,7 @@ class Song(Title):
|
||||
raise ValueError(f"Song track cannot be {track}")
|
||||
if disc <= 0:
|
||||
raise ValueError(f"Song disc cannot be {disc}")
|
||||
if year <= 0:
|
||||
if year is not None and year <= 0:
|
||||
raise ValueError(f"Song year cannot be {year}")
|
||||
if not release_type:
|
||||
raise ValueError("Song release_type must be provided")
|
||||
@@ -141,9 +138,18 @@ class Song(Title):
|
||||
|
||||
def __str__(self) -> str:
|
||||
return "{artist} - {album} ({year}) / {track:02}. {name}".format(
|
||||
artist=self.artist, album=self.album, year=self.year, track=self.track, name=self.name
|
||||
artist=self.artist, album=self.album, year=self.year or "?", track=self.track, name=self.name
|
||||
).strip()
|
||||
|
||||
def matches_wanted(self, wanted: Collection[str]) -> bool:
|
||||
"""Whether a parsed ``-w`` key set selects this song.
|
||||
|
||||
A song shares the episode key space, its disc reading as the season and its track
|
||||
as the episode, so ``-w 1-5`` takes tracks 1 to 5 and ``-w 2x3`` takes disc 2
|
||||
track 3. A song has no parts and no air date, so it answers to one key only.
|
||||
"""
|
||||
return f"{self.disc}x{self.track}" in wanted
|
||||
|
||||
def build_template_context(self, media_info: MediaInfo, show_service: bool = True) -> dict:
|
||||
"""Build template context dictionary from MediaInfo."""
|
||||
context = self.build_base_template_context(media_info, show_service)
|
||||
@@ -262,10 +268,11 @@ class Music(SortedKeyList, ABC):
|
||||
year = self.year or first_song.year or "?"
|
||||
return f"{artist} - {title} ({year})"
|
||||
|
||||
def tree(self, verbose: bool = False) -> Any:
|
||||
def tree(self, verbose: bool = False) -> RenderableType:
|
||||
# verbose is the Titles_T contract; a release always renders its full tracklist
|
||||
from unshackle.core.music.renderer import MusicRenderer
|
||||
|
||||
return MusicRenderer().render(self, verbose=verbose)
|
||||
return MusicRenderer().render(self)
|
||||
|
||||
|
||||
class Album(Music):
|
||||
|
||||
@@ -1,137 +1,5 @@
|
||||
import re
|
||||
from abc import ABC
|
||||
from typing import Any, Iterable, Optional, Union
|
||||
|
||||
from langcodes import Language
|
||||
from pymediainfo import MediaInfo
|
||||
from rich.tree import Tree
|
||||
from sortedcontainers import SortedKeyList
|
||||
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.titles.title import Title
|
||||
from unshackle.core.utilities import sanitize_filename
|
||||
from unshackle.core.utils.template_formatter import TemplateFormatter, detect_spacer
|
||||
|
||||
|
||||
class Song(Title):
|
||||
def __init__(
|
||||
self,
|
||||
id_: Any,
|
||||
service: type,
|
||||
name: str,
|
||||
artist: str,
|
||||
album: str,
|
||||
track: int,
|
||||
disc: int,
|
||||
year: int,
|
||||
language: Optional[Union[str, Language]] = None,
|
||||
data: Optional[Any] = None,
|
||||
) -> None:
|
||||
super().__init__(id_, service, language, data)
|
||||
|
||||
if not name:
|
||||
raise ValueError("Song name must be provided")
|
||||
if not isinstance(name, str):
|
||||
raise TypeError(f"Expected name to be a str, not {name!r}")
|
||||
|
||||
if not artist:
|
||||
raise ValueError("Song artist must be provided")
|
||||
if not isinstance(artist, str):
|
||||
raise TypeError(f"Expected artist to be a str, not {artist!r}")
|
||||
|
||||
if not album:
|
||||
raise ValueError("Song album must be provided")
|
||||
if not isinstance(album, str):
|
||||
raise TypeError(f"Expected album to be a str, not {album!r}")
|
||||
|
||||
if not track:
|
||||
raise ValueError("Song track must be provided")
|
||||
if not isinstance(track, int):
|
||||
raise TypeError(f"Expected track to be an int, not {track!r}")
|
||||
|
||||
if not disc:
|
||||
raise ValueError("Song disc must be provided")
|
||||
if not isinstance(disc, int):
|
||||
raise TypeError(f"Expected disc to be an int, not {disc!r}")
|
||||
|
||||
if not year:
|
||||
raise ValueError("Song year must be provided")
|
||||
if not isinstance(year, int):
|
||||
raise TypeError(f"Expected year to be an int, not {year!r}")
|
||||
|
||||
name = name.strip()
|
||||
artist = artist.strip()
|
||||
album = album.strip()
|
||||
|
||||
if track <= 0:
|
||||
raise ValueError(f"Song track cannot be {track}")
|
||||
if disc <= 0:
|
||||
raise ValueError(f"Song disc cannot be {disc}")
|
||||
if year <= 0:
|
||||
raise ValueError(f"Song year cannot be {year}")
|
||||
|
||||
self.name = name
|
||||
self.artist = artist
|
||||
self.album = album
|
||||
self.track = track
|
||||
self.disc = disc
|
||||
self.year = year
|
||||
|
||||
def __str__(self) -> str:
|
||||
return "{artist} - {album} ({year}) / {track:02}. {name}".format(
|
||||
artist=self.artist, album=self.album, year=self.year, track=self.track, name=self.name
|
||||
).strip()
|
||||
|
||||
def build_template_context(self, media_info: MediaInfo, show_service: bool = True) -> dict:
|
||||
"""Build template context dictionary from MediaInfo."""
|
||||
context = self.build_base_template_context(media_info, show_service)
|
||||
context["title"] = self.name.replace("$", "S")
|
||||
context["year"] = self.year or ""
|
||||
context["track_number"] = f"{self.track:02}"
|
||||
context["artist"] = self.artist.replace("$", "S")
|
||||
context["album"] = self.album.replace("$", "S")
|
||||
context["disc"] = f"{self.disc:02}" if self.disc > 1 else ""
|
||||
return context
|
||||
|
||||
def get_filename(self, media_info: MediaInfo, folder: bool = False, show_service: bool = True) -> str:
|
||||
if folder:
|
||||
template = config.get_folder_template("songs")
|
||||
if template:
|
||||
context = self.build_template_context(media_info, show_service)
|
||||
spacer = detect_spacer(template) # one style for the whole path
|
||||
segments = [
|
||||
TemplateFormatter(seg, spacer).format(context)
|
||||
for seg in re.split(r"[\\/]", template)
|
||||
if seg.strip()
|
||||
]
|
||||
return "/".join(s for s in segments if s)
|
||||
name = f"{self.artist} - {self.album}"
|
||||
if self.year:
|
||||
name += f" ({self.year})"
|
||||
return sanitize_filename(name, " ")
|
||||
|
||||
formatter = TemplateFormatter(config.output_template["songs"])
|
||||
context = self.build_template_context(media_info, show_service)
|
||||
return formatter.format(context)
|
||||
|
||||
|
||||
class Album(SortedKeyList, ABC):
|
||||
def __init__(self, iterable: Optional[Iterable] = None):
|
||||
super().__init__(iterable, key=lambda x: (x.album, x.disc, x.track, x.year or 0))
|
||||
|
||||
def __str__(self) -> str:
|
||||
if not self:
|
||||
return super().__str__()
|
||||
return f"{self[0].artist} - {self[0].album} ({self[0].year or '?'})"
|
||||
|
||||
def tree(self, verbose: bool = False) -> Tree:
|
||||
num_songs = len(self)
|
||||
tree = Tree(f"{num_songs} Song{['s', ''][num_songs == 1]}", guide_style="bright_black")
|
||||
if verbose:
|
||||
for song in self:
|
||||
tree.add(f"[bold]Track {song.track:02}.[/] [bright_black]({song.name})", guide_style="bright_black")
|
||||
|
||||
return tree
|
||||
"""Deprecated. Import from unshackle.core.titles.music instead."""
|
||||
|
||||
from unshackle.core.titles.music import Album, Song # noqa: F401
|
||||
|
||||
__all__ = ("Song", "Album")
|
||||
|
||||
@@ -86,7 +86,7 @@ class Audio(Track):
|
||||
codec: An Audio.Codec enum representing the audio codec.
|
||||
If not specified, MediaInfo will be used to retrieve the codec
|
||||
once the track has been downloaded.
|
||||
bitrate: A number or float representing the average bandwidth in bytes/s.
|
||||
bitrate: A number or float representing the average bandwidth in bits/s.
|
||||
Float values are rounded up to the nearest integer.
|
||||
channels: A number, float, or string representing the number of audio channels.
|
||||
Strings may represent numbers or floats. Expanded layouts like 7.1.1 is
|
||||
|
||||
@@ -164,6 +164,11 @@ class SeasonRange(click.ParamType):
|
||||
MAX_DATE_SPAN = 1000
|
||||
|
||||
DATE_TOKEN = re.compile(r"^(?P<left>\d{4}-\d{2}-\d{2})(:(?P<right>\d{4}-\d{2}-\d{2}))?$")
|
||||
TOKEN = re.compile(
|
||||
r"^(?:S(?P<season>\d+)(E(?P<episode>\d+)(\.(?P<part>\d+))?)?"
|
||||
r"|((?P<disc>\d+)x)?(?P<track>\d+))$",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
def parse_date_token(self, token: str, match: re.Match) -> list[str]:
|
||||
"""Expand an ISO date token or ':'-separated date range into ISO day keys."""
|
||||
@@ -179,6 +184,25 @@ class SeasonRange(click.ParamType):
|
||||
self.fail(f"Invalid range, a date range cannot span more than {self.MAX_DATE_SPAN} days: {token}")
|
||||
return [(left + timedelta(days=i)).isoformat() for i in range(span)]
|
||||
|
||||
def token_sides(self, match: re.Match) -> tuple[int, Optional[int], Optional[int]]:
|
||||
"""Read one side of a token as (season, episode, part), episode/part None when absent.
|
||||
|
||||
A music disc x track token shares this key space, disc reading as the season and
|
||||
track as the episode. An omitted disc is disc 1, not every disc: a bare number is
|
||||
the number the tracklist shows for a single-disc release, and widening it would
|
||||
silently add tracks on a multi-disc release.
|
||||
"""
|
||||
if match.group("season") is not None:
|
||||
episode = match.group("episode")
|
||||
part = match.group("part")
|
||||
return (
|
||||
int(match.group("season")),
|
||||
int(episode) if episode is not None else None,
|
||||
int(part) if part is not None else None,
|
||||
)
|
||||
disc = match.group("disc")
|
||||
return int(disc) if disc is not None else 1, int(match.group("track")), None
|
||||
|
||||
def parse_tokens(self, *tokens: str) -> list[str]:
|
||||
"""
|
||||
Parse multiple tokens or ranged tokens as '{s}x{e}' strings.
|
||||
@@ -191,6 +215,10 @@ class SeasonRange(click.ParamType):
|
||||
Dated content is addressed by ISO air date. A date range uses ':' only, because
|
||||
a date's own '-' separators are not a range separator.
|
||||
|
||||
A music release uses the same keys, its disc reading as the season and its track
|
||||
as the episode. A track is addressed as '{d}x{t}', or by its number alone, which
|
||||
is a track on disc 1.
|
||||
|
||||
Supports exclusioning by putting a `-` before the token.
|
||||
|
||||
Example:
|
||||
@@ -209,6 +237,10 @@ class SeasonRange(click.ParamType):
|
||||
["2026-08-11"]
|
||||
>>> sr.parse_tokens("2026-08-01:2026-08-03", "-2026-08-02")
|
||||
["2026-08-01", "2026-08-03"]
|
||||
>>> sr.parse_tokens("3")
|
||||
["1x3"]
|
||||
>>> sr.parse_tokens("1-3", "2x1")
|
||||
["1x1", "1x2", "1x3", "2x1"]
|
||||
"""
|
||||
if len(tokens) == 0:
|
||||
return []
|
||||
@@ -223,10 +255,7 @@ class SeasonRange(click.ParamType):
|
||||
if date_match:
|
||||
(computed if not exclude else exclusions).extend(self.parse_date_token(token, date_match))
|
||||
continue
|
||||
parsed = [
|
||||
re.match(r"^S(?P<season>\d+)(E(?P<episode>\d+)(\.(?P<part>\d+))?)?$", x, re.IGNORECASE)
|
||||
for x in re.split(r"[:-]", token)
|
||||
]
|
||||
parsed = [self.TOKEN.match(x) for x in re.split(r"[:-]", token)]
|
||||
if len(parsed) > 2:
|
||||
self.fail(f"Invalid token, only a left and right range is acceptable: {token}")
|
||||
if len(parsed) == 1:
|
||||
@@ -235,17 +264,10 @@ class SeasonRange(click.ParamType):
|
||||
parsed.append(parsed[0])
|
||||
if any(x is None for x in parsed):
|
||||
self.fail(f"Invalid token, syntax error occurred: {token}")
|
||||
left, right = parsed[0], parsed[1]
|
||||
from_season = int(left.group("season")) # type: ignore[union-attr]
|
||||
from_episode_raw = left.group("episode") # type: ignore[union-attr]
|
||||
from_episode = int(from_episode_raw) if from_episode_raw is not None else self.MIN_EPISODE
|
||||
from_part_raw = left.group("part") # type: ignore[union-attr]
|
||||
from_part = int(from_part_raw) if from_part_raw is not None else None
|
||||
to_season = int(right.group("season")) # type: ignore[union-attr]
|
||||
to_episode_raw = right.group("episode") # type: ignore[union-attr]
|
||||
to_episode = int(to_episode_raw) if to_episode_raw is not None else self.MAX_EPISODE
|
||||
to_part_raw = right.group("part") # type: ignore[union-attr]
|
||||
to_part = int(to_part_raw) if to_part_raw is not None else None
|
||||
from_season, from_episode_raw, from_part = self.token_sides(parsed[0]) # type: ignore[arg-type]
|
||||
from_episode = from_episode_raw if from_episode_raw is not None else self.MIN_EPISODE
|
||||
to_season, to_episode_raw, to_part = self.token_sides(parsed[1]) # type: ignore[arg-type]
|
||||
to_episode = to_episode_raw if to_episode_raw is not None else self.MAX_EPISODE
|
||||
if from_season > to_season:
|
||||
self.fail(f"Invalid range, left side season cannot be bigger than right side season: {token}")
|
||||
if from_season == to_season and from_episode > to_episode:
|
||||
|
||||
@@ -138,6 +138,19 @@ def build_context(
|
||||
return context
|
||||
|
||||
|
||||
def season_context(context: dict[str, str], folder: Path) -> dict[str, str]:
|
||||
"""Blank the file-level variables so a season/album hook describes the folder."""
|
||||
out = dict(context)
|
||||
for key in ("filepath", "filename", "ext", "sidecars", "episode", "episode_name"):
|
||||
out[key] = ""
|
||||
if out.get("album"): # music: the album stands in for the season
|
||||
for key in ("track_number", "disc", "isrc"):
|
||||
if key in out:
|
||||
out[key] = ""
|
||||
out["title"] = out["title_raw"] = out["album"]
|
||||
return out | {"folder": str(folder)}
|
||||
|
||||
|
||||
def _entries(event: str, mode: str, overrides: Sequence[str] = ()) -> Iterator[str]:
|
||||
"""Commands configured for this event and mode; --postscript replaces the config list."""
|
||||
if overrides:
|
||||
|
||||
@@ -5,11 +5,12 @@ import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Optional, Union
|
||||
from typing import Any, Optional, Union
|
||||
from xml.sax.saxutils import escape
|
||||
|
||||
from unshackle.core import binaries
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.music.tagger import write_music_metadata
|
||||
from unshackle.core.providers import (
|
||||
ExternalIds,
|
||||
fuzzy_match,
|
||||
@@ -18,6 +19,7 @@ from unshackle.core.providers import (
|
||||
)
|
||||
from unshackle.core.titles.episode import Episode
|
||||
from unshackle.core.titles.movie import Movie
|
||||
from unshackle.core.titles.music import Song
|
||||
from unshackle.core.titles.title import Title
|
||||
from unshackle.core.utils.subprocess import log_tool_run
|
||||
|
||||
@@ -87,8 +89,20 @@ def tag_file(
|
||||
tvdb_id: Optional[int] = None,
|
||||
anilist_id: Optional[Union[int, str]] = None,
|
||||
anime: bool = False,
|
||||
session: Any = None,
|
||||
) -> None:
|
||||
log.debug("Tagging file %s with title %r", path, title)
|
||||
|
||||
if isinstance(title, Song):
|
||||
try:
|
||||
music_result = write_music_metadata(path, title, session=session)
|
||||
except Exception as e: # the file already moved; a tagging fault must warn, not abort the run
|
||||
log.warning("Music tagging failed for %s: %s", path.name, e)
|
||||
return
|
||||
if music_result.skipped and music_result.reason:
|
||||
log.warning("Music metadata skipped for %s: %s", path.name, music_result.reason)
|
||||
return
|
||||
|
||||
custom_tags: dict[str, str] = {}
|
||||
|
||||
if config.tag and config.tag_group_name:
|
||||
|
||||
Reference in New Issue
Block a user