forked from kenzuya/unshackle
refactor(core)!: drop leading underscores from internal definitions
Renames 314 defs and 41 module/class-level constants. Keeps 11 names underscored where the stripped form collides in scope, plus 5.5.0 shims for the three symbols external service repos call.
This commit is contained in:
@@ -56,7 +56,7 @@ def verify_music_audio(
|
||||
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))
|
||||
duration = duration_seconds(getattr(audio_track, "duration", None))
|
||||
expected_duration = _expected_duration(song, track)
|
||||
warnings: list[str] = []
|
||||
if expected_duration and duration:
|
||||
@@ -69,15 +69,15 @@ def verify_music_audio(
|
||||
result = MusicAudioIntegrityResult(
|
||||
path=path,
|
||||
size=size,
|
||||
codec=_first_text(
|
||||
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(
|
||||
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),
|
||||
@@ -115,13 +115,13 @@ 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"))
|
||||
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"))
|
||||
value = first_float(track_data.get("duration"), metadata.get("duration"))
|
||||
if value:
|
||||
return value
|
||||
return None
|
||||
@@ -140,7 +140,7 @@ def _expected_size(track: Any) -> Optional[int]:
|
||||
data.get("metadata") if isinstance(data.get("metadata"), dict) else {},
|
||||
]
|
||||
for source in sources:
|
||||
value = _first_int(
|
||||
value = first_int(
|
||||
source.get("content_length"),
|
||||
source.get("contentLength"),
|
||||
source.get("file_size"),
|
||||
@@ -152,8 +152,8 @@ def _expected_size(track: Any) -> Optional[int]:
|
||||
return None
|
||||
|
||||
|
||||
def _duration_seconds(value: Any) -> Optional[float]:
|
||||
number = _first_float(value)
|
||||
def duration_seconds(value: Any) -> Optional[float]:
|
||||
number = first_float(value)
|
||||
if number is None:
|
||||
return None
|
||||
if number > 1000:
|
||||
@@ -161,7 +161,7 @@ def _duration_seconds(value: Any) -> Optional[float]:
|
||||
return number
|
||||
|
||||
|
||||
def _first_text(*values: Any) -> str:
|
||||
def first_text(*values: Any) -> str:
|
||||
for value in values:
|
||||
text = str(value or "").strip()
|
||||
if text:
|
||||
@@ -169,7 +169,7 @@ def _first_text(*values: Any) -> str:
|
||||
return ""
|
||||
|
||||
|
||||
def _first_float(*values: Any) -> Optional[float]:
|
||||
def first_float(*values: Any) -> Optional[float]:
|
||||
for value in values:
|
||||
if value in (None, "", [], {}):
|
||||
continue
|
||||
@@ -181,8 +181,8 @@ def _first_float(*values: Any) -> Optional[float]:
|
||||
return None
|
||||
|
||||
|
||||
def _first_int(*values: Any) -> Optional[int]:
|
||||
value = _first_float(*values)
|
||||
def first_int(*values: Any) -> Optional[int]:
|
||||
value = first_float(*values)
|
||||
return int(value) if value is not None else None
|
||||
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@ class MusicPlanner:
|
||||
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(
|
||||
released=self.first_text(
|
||||
getattr(music, "released", None),
|
||||
getattr(music, "release_date", None),
|
||||
first_data.get("release_date"),
|
||||
@@ -37,15 +37,15 @@ class MusicPlanner:
|
||||
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),
|
||||
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)
|
||||
options = self.get_options(song)
|
||||
selected = options[0] if options else None
|
||||
if selected:
|
||||
selected_options.append(selected)
|
||||
@@ -60,33 +60,33 @@ class MusicPlanner:
|
||||
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)
|
||||
quality = self.quality_summary_from_options(selected_options)
|
||||
if quality:
|
||||
plan.quality_requested = quality
|
||||
|
||||
return plan
|
||||
|
||||
def _get_options(self, song: Song) -> list[MusicTrackOption]:
|
||||
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)
|
||||
option = self.option_from_song(song)
|
||||
return [option] if option else []
|
||||
|
||||
@staticmethod
|
||||
def _option_from_song(song: Song) -> MusicTrackOption | None:
|
||||
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"))
|
||||
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)
|
||||
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"))
|
||||
@@ -97,7 +97,7 @@ class MusicPlanner:
|
||||
bit_depth=bit_depth,
|
||||
sample_rate=sample_rate,
|
||||
bitrate=bitrate,
|
||||
channels=MusicPlanner._first_number(data.get("channels"), metadata.get("channels")),
|
||||
channels=MusicPlanner.first_number(data.get("channels"), metadata.get("channels")),
|
||||
lossless=lossless,
|
||||
hires=hires,
|
||||
atmos=atmos,
|
||||
@@ -106,7 +106,7 @@ class MusicPlanner:
|
||||
quality_label=quality,
|
||||
)
|
||||
|
||||
def _quality_requested(self, music: Music) -> str:
|
||||
def quality_requested(self, music: Music) -> str:
|
||||
service_quality = getattr(self.service, "quality", None)
|
||||
if service_quality:
|
||||
quality_map = {
|
||||
@@ -121,10 +121,10 @@ class MusicPlanner:
|
||||
if not first_song:
|
||||
return ""
|
||||
data = first_song.data if isinstance(first_song.data, dict) else {}
|
||||
return self._first_text(data.get("quality"))
|
||||
return self.first_text(data.get("quality"))
|
||||
|
||||
@staticmethod
|
||||
def _first_text(*values: Any) -> str:
|
||||
def first_text(*values: Any) -> str:
|
||||
for value in values:
|
||||
if value in (None, ""):
|
||||
continue
|
||||
@@ -134,7 +134,7 @@ class MusicPlanner:
|
||||
return ""
|
||||
|
||||
@staticmethod
|
||||
def _first_number(*values: Any) -> float | None:
|
||||
def first_number(*values: Any) -> float | None:
|
||||
for value in values:
|
||||
if value in (None, ""):
|
||||
continue
|
||||
@@ -145,7 +145,7 @@ class MusicPlanner:
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _codec_from_quality(value: str) -> str:
|
||||
def codec_from_quality(value: str) -> str:
|
||||
lowered = value.lower()
|
||||
for codec in ("flac", "alac", "aac", "mp3", "wav", "aiff"):
|
||||
if codec in lowered:
|
||||
@@ -153,7 +153,7 @@ class MusicPlanner:
|
||||
return ""
|
||||
|
||||
@staticmethod
|
||||
def _quality_numbers(value: str) -> tuple[int | None, int | None]:
|
||||
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())
|
||||
@@ -165,14 +165,14 @@ class MusicPlanner:
|
||||
return bit_depth, sample_rate
|
||||
|
||||
@staticmethod
|
||||
def _bitrate_from_quality(value: str) -> int | None:
|
||||
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:
|
||||
def quality_summary_from_options(options: list[MusicTrackOption]) -> str:
|
||||
if not options:
|
||||
return ""
|
||||
|
||||
@@ -194,19 +194,19 @@ class MusicPlanner:
|
||||
return "AAC"
|
||||
if "MP3" in codecs:
|
||||
return "MP3"
|
||||
return MusicPlanner._first_text(*labels)
|
||||
return MusicPlanner.first_text(*labels)
|
||||
|
||||
@staticmethod
|
||||
def _sum_duration(music: Music) -> int | None:
|
||||
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"))
|
||||
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:
|
||||
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
|
||||
|
||||
|
||||
@@ -47,9 +47,9 @@ class MusicRenderer:
|
||||
kind = self.display_kind(music.kind)
|
||||
explicit = any(bool(getattr(song, "explicit", None)) for song in music)
|
||||
total_tracks = getattr(music, "total_tracks", None) or len(music)
|
||||
total_discs = getattr(music, "total_discs", None) or self._max_value(music, "disc")
|
||||
released = self._format_release_date(
|
||||
self._first_value(
|
||||
total_discs = getattr(music, "total_discs", None) or self.max_value(music, "disc")
|
||||
released = self.format_release_date(
|
||||
self.first_value(
|
||||
getattr(music, "released", None),
|
||||
getattr(music, "release_date", None),
|
||||
data.get("release_date"),
|
||||
@@ -58,23 +58,23 @@ class MusicRenderer:
|
||||
metadata.get("released_at"),
|
||||
)
|
||||
)
|
||||
length = self._format_total_duration(getattr(music, "total_duration", None) or self._sum_duration(music))
|
||||
quality = self._quality_summary(
|
||||
self._first_text(
|
||||
length = self.format_total_duration(getattr(music, "total_duration", None) or self.sum_duration(music))
|
||||
quality = self.quality_summary(
|
||||
self.first_text(
|
||||
getattr(music, "quality", None),
|
||||
data.get("quality"),
|
||||
metadata.get("quality"),
|
||||
metadata.get("quality_label"),
|
||||
),
|
||||
lossless=self._as_bool(self._first_value(data.get("lossless"), metadata.get("lossless"))),
|
||||
hires=self._as_bool(self._first_value(data.get("hires"), metadata.get("hires"))),
|
||||
lossless=self.as_bool(self.first_value(data.get("lossless"), metadata.get("lossless"))),
|
||||
hires=self.as_bool(self.first_value(data.get("hires"), metadata.get("hires"))),
|
||||
)
|
||||
|
||||
grid = self._metadata_grid()
|
||||
grid = self.metadata_grid()
|
||||
|
||||
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))
|
||||
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 year:
|
||||
@@ -103,8 +103,8 @@ class MusicRenderer:
|
||||
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")
|
||||
option = self._option_from_song(song)
|
||||
node = tree.add(self.song_line(song, music), guide_style="bright_black")
|
||||
option = self.option_from_song(song)
|
||||
if option:
|
||||
node.add(option, guide_style="bright_black")
|
||||
|
||||
@@ -124,16 +124,16 @@ class MusicRenderer:
|
||||
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)
|
||||
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()
|
||||
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))
|
||||
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:
|
||||
@@ -163,12 +163,12 @@ class MusicRenderer:
|
||||
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")
|
||||
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")
|
||||
node.add(self.option_line(option), guide_style="bright_black")
|
||||
|
||||
hidden = total - len(visible_songs)
|
||||
if hidden > 0:
|
||||
@@ -178,7 +178,7 @@ class MusicRenderer:
|
||||
return Panel(tree, title="Available Tracks", box=box.SQUARE, border_style="bright_black")
|
||||
|
||||
@staticmethod
|
||||
def _metadata_grid() -> Table:
|
||||
def metadata_grid() -> Table:
|
||||
grid = Table.grid(padding=(0, 2))
|
||||
grid.add_column(style="orchid1", no_wrap=True)
|
||||
grid.add_column()
|
||||
@@ -205,7 +205,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 | MusicDownloadPlan) -> 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,13 +217,13 @@ 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 | str:
|
||||
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 = 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(
|
||||
data.get("unavailable_reason"),
|
||||
data.get("skip_reason"),
|
||||
metadata.get("unavailable_reason"),
|
||||
@@ -235,9 +235,9 @@ class MusicRenderer:
|
||||
badges = []
|
||||
if song.explicit:
|
||||
badges.append(("E", "bold bright_red"))
|
||||
if self._as_bool(self._first_value(data.get("atmos"), metadata.get("atmos"))):
|
||||
if self.as_bool(self.first_value(data.get("atmos"), metadata.get("atmos"))):
|
||||
badges.append(("Atmos", "magenta"))
|
||||
if self._is_hires_quality(quality):
|
||||
if self.is_hires_quality(quality):
|
||||
badges.append(("Hi-Res", "gold1"))
|
||||
|
||||
details = []
|
||||
@@ -247,43 +247,43 @@ class MusicRenderer:
|
||||
details.append(duration)
|
||||
if not details and not badges:
|
||||
return ""
|
||||
return self._format_option_text(details, badges)
|
||||
return self.format_option_text(details, badges)
|
||||
|
||||
def _option_line(self, option: MusicTrackOption) -> Text:
|
||||
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))
|
||||
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)}")
|
||||
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))
|
||||
parts.append(self.format_channels(option.channels))
|
||||
if option.duration:
|
||||
parts.append(self._format_duration(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):
|
||||
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)
|
||||
return self.format_option_text(parts, badges)
|
||||
|
||||
@staticmethod
|
||||
def _kind_text(kind: str, *, explicit: bool = False) -> Text:
|
||||
def kind_text(kind: str, *, explicit: bool = False) -> Text:
|
||||
text = Text(str(kind))
|
||||
if explicit:
|
||||
text.append(" Explicit", style="bold red")
|
||||
return text
|
||||
|
||||
@staticmethod
|
||||
def _format_option_text(parts: list[str], badges: list[tuple[str, str]]) -> Text:
|
||||
def format_option_text(parts: list[str], badges: list[tuple[str, str]]) -> Text:
|
||||
text = Text(style="text2")
|
||||
first = True
|
||||
for part in parts:
|
||||
@@ -301,13 +301,13 @@ class MusicRenderer:
|
||||
return text
|
||||
|
||||
@staticmethod
|
||||
def _format_option_parts(parts: list[str]) -> str:
|
||||
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]:
|
||||
def split_quality_label(value: str, codec: str = "") -> list[str]:
|
||||
text = str(value or "").strip()
|
||||
if not text:
|
||||
return []
|
||||
@@ -316,7 +316,7 @@ class MusicRenderer:
|
||||
return [text] if text else []
|
||||
|
||||
@staticmethod
|
||||
def _is_cd_option(option: MusicTrackOption) -> bool:
|
||||
def is_cd_option(option: MusicTrackOption) -> bool:
|
||||
codec = str(option.codec or "").upper()
|
||||
if codec not in {"FLAC", "ALAC", "WAV", "AIFF"}:
|
||||
return False
|
||||
@@ -325,7 +325,7 @@ class MusicRenderer:
|
||||
return "16-bit/44.1" in str(option.quality_label or "").lower()
|
||||
|
||||
@staticmethod
|
||||
def _format_sample_rate(value: Any) -> str:
|
||||
def format_sample_rate(value: Any) -> str:
|
||||
try:
|
||||
sample_rate = float(value)
|
||||
except (TypeError, ValueError):
|
||||
@@ -337,7 +337,7 @@ class MusicRenderer:
|
||||
return f"{sample_rate:g} kHz"
|
||||
|
||||
@staticmethod
|
||||
def _format_channels(value: Any) -> str:
|
||||
def format_channels(value: Any) -> str:
|
||||
try:
|
||||
channels = float(value)
|
||||
except (TypeError, ValueError):
|
||||
@@ -351,7 +351,7 @@ class MusicRenderer:
|
||||
return f"{channels:g}"
|
||||
|
||||
@staticmethod
|
||||
def _first_text(*values: Any) -> str:
|
||||
def first_text(*values: Any) -> str:
|
||||
for value in values:
|
||||
if value is None:
|
||||
continue
|
||||
@@ -361,7 +361,7 @@ class MusicRenderer:
|
||||
if nested:
|
||||
return str(nested).strip()
|
||||
elif isinstance(value, (list, tuple)):
|
||||
text = MusicRenderer._first_text(*value)
|
||||
text = MusicRenderer.first_text(*value)
|
||||
if text:
|
||||
return text
|
||||
else:
|
||||
@@ -371,14 +371,14 @@ class MusicRenderer:
|
||||
return ""
|
||||
|
||||
@staticmethod
|
||||
def _first_value(*values: Any) -> Any:
|
||||
def first_value(*values: Any) -> Any:
|
||||
for value in values:
|
||||
if value is not None and value != "":
|
||||
return value
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _as_bool(value: Any) -> bool:
|
||||
def as_bool(value: Any) -> bool:
|
||||
if isinstance(value, bool):
|
||||
return value
|
||||
if isinstance(value, str):
|
||||
@@ -386,7 +386,7 @@ class MusicRenderer:
|
||||
return bool(value)
|
||||
|
||||
@staticmethod
|
||||
def _format_duration(value: Any) -> str:
|
||||
def format_duration(value: Any) -> str:
|
||||
if value in (None, ""):
|
||||
return ""
|
||||
try:
|
||||
@@ -400,7 +400,7 @@ class MusicRenderer:
|
||||
return f"{minutes}:{seconds:02}"
|
||||
|
||||
@staticmethod
|
||||
def _format_total_duration(value: Any) -> str:
|
||||
def format_total_duration(value: Any) -> str:
|
||||
if value in (None, ""):
|
||||
return ""
|
||||
try:
|
||||
@@ -416,7 +416,7 @@ class MusicRenderer:
|
||||
return f"{minutes}m {seconds:02}s"
|
||||
|
||||
@staticmethod
|
||||
def _format_release_date(value: Any) -> str:
|
||||
def format_release_date(value: Any) -> str:
|
||||
if value in (None, ""):
|
||||
return ""
|
||||
text = str(value).strip()
|
||||
@@ -450,7 +450,7 @@ class MusicRenderer:
|
||||
return f"{month_names[month - 1]} {day}, {year}"
|
||||
|
||||
@classmethod
|
||||
def _quality_summary(cls, value: Any, *, lossless: bool = False, hires: bool = False) -> str:
|
||||
def quality_summary(cls, value: Any, *, lossless: bool = False, hires: bool = False) -> str:
|
||||
text = str(value or "").strip()
|
||||
lowered = text.lower()
|
||||
if not text:
|
||||
@@ -462,7 +462,7 @@ class MusicRenderer:
|
||||
if "atmos" in lowered:
|
||||
return "Dolby Atmos"
|
||||
if any(codec in lowered for codec in ("flac", "alac", "wav", "aiff")):
|
||||
return "Hi-Res Lossless" if cls._is_hires_quality(text) else "Lossless"
|
||||
return "Hi-Res Lossless" if cls.is_hires_quality(text) else "Lossless"
|
||||
if "lossless" in lowered:
|
||||
return "Hi-Res Lossless" if "hi-res" in lowered or hires else "Lossless"
|
||||
if "aac" in lowered:
|
||||
@@ -472,7 +472,7 @@ class MusicRenderer:
|
||||
return text
|
||||
|
||||
@staticmethod
|
||||
def _is_hires_quality(value: str) -> bool:
|
||||
def is_hires_quality(value: str) -> bool:
|
||||
lowered = value.lower()
|
||||
bit_depth = None
|
||||
sample_rate = None
|
||||
@@ -488,12 +488,12 @@ class MusicRenderer:
|
||||
return bool((bit_depth and bit_depth > 16) or (sample_rate and sample_rate > 48))
|
||||
|
||||
@staticmethod
|
||||
def _sum_duration(music: Music) -> int:
|
||||
def sum_duration(music: Music) -> int:
|
||||
total = 0
|
||||
for song in music:
|
||||
data = song.data if isinstance(song.data, dict) else {}
|
||||
metadata = data.get("metadata") if isinstance(data.get("metadata"), dict) else {}
|
||||
value = MusicRenderer._first_value(data.get("duration"), metadata.get("duration"))
|
||||
value = MusicRenderer.first_value(data.get("duration"), metadata.get("duration"))
|
||||
try:
|
||||
total += int(float(value or 0))
|
||||
except (TypeError, ValueError):
|
||||
@@ -501,7 +501,7 @@ class MusicRenderer:
|
||||
return total
|
||||
|
||||
@staticmethod
|
||||
def _max_value(music: Music, attr: str) -> int:
|
||||
def max_value(music: Music, attr: str) -> int:
|
||||
values = [getattr(song, attr, 0) or 0 for song in music]
|
||||
return max(values, default=0)
|
||||
|
||||
|
||||
@@ -74,49 +74,49 @@ def write_music_metadata(path: Path, song: Any, *, session: Any = None, source_m
|
||||
if extension in {".m4a", ".mp4"} and MP4 is None:
|
||||
return MusicMetadataResult(skipped=True, reason="install mutagen to write MP4/M4A tags")
|
||||
|
||||
tags = _build_tag_values(song, source_md5=source_md5)
|
||||
artwork_url = _first_text(getattr(song, "artwork_url", None), _metadata(song).get("artwork_url"))
|
||||
cover_data, mime_type = _download_cover(session, artwork_url)
|
||||
tags = build_tag_values(song, source_md5=source_md5)
|
||||
artwork_url = first_text(getattr(song, "artwork_url", None), _metadata(song).get("artwork_url"))
|
||||
cover_data, mime_type = download_cover(session, artwork_url)
|
||||
|
||||
if extension == ".flac":
|
||||
_write_flac_tags(path, tags, cover_data, mime_type)
|
||||
write_flac_tags(path, tags, cover_data, mime_type)
|
||||
elif extension == ".mp3":
|
||||
_write_mp3_tags(path, tags, cover_data, mime_type)
|
||||
write_mp3_tags(path, tags, cover_data, mime_type)
|
||||
else:
|
||||
_write_mp4_tags(path, tags, cover_data, mime_type)
|
||||
write_mp4_tags(path, tags, cover_data, mime_type)
|
||||
|
||||
return MusicMetadataResult(written=True, artwork_embedded=bool(cover_data))
|
||||
|
||||
|
||||
def _build_tag_values(song: Any, *, source_md5: str = "") -> dict[str, str]:
|
||||
def build_tag_values(song: Any, *, source_md5: str = "") -> dict[str, str]:
|
||||
metadata = _metadata(song)
|
||||
track_number = _string_tag(getattr(song, "track", None) or metadata.get("track_number"))
|
||||
track_total = _string_tag(getattr(song, "total_tracks", None) or metadata.get("total_tracks"))
|
||||
disc_number = _string_tag(getattr(song, "disc", None) or metadata.get("disc_number"))
|
||||
disc_total = _string_tag(getattr(song, "total_discs", None) or metadata.get("total_discs"))
|
||||
explicit = _as_bool(getattr(song, "explicit", None), metadata.get("explicit"), metadata.get("parental_warning"))
|
||||
track_number = string_tag(getattr(song, "track", None) or metadata.get("track_number"))
|
||||
track_total = string_tag(getattr(song, "total_tracks", None) or metadata.get("total_tracks"))
|
||||
disc_number = string_tag(getattr(song, "disc", None) or metadata.get("disc_number"))
|
||||
disc_total = string_tag(getattr(song, "total_discs", None) or metadata.get("total_discs"))
|
||||
explicit = as_bool(getattr(song, "explicit", None), metadata.get("explicit"), metadata.get("parental_warning"))
|
||||
|
||||
tags = {
|
||||
"TITLE": _first_text(getattr(song, "name", None), metadata.get("title")),
|
||||
"ARTIST": _first_text(getattr(song, "artist", None), metadata.get("artist"), metadata.get("performer")),
|
||||
"ALBUM": _first_text(getattr(song, "album", None), metadata.get("album")),
|
||||
"ALBUMARTIST": _first_text(getattr(song, "album_artist", None), metadata.get("album_artist")),
|
||||
"TITLE": first_text(getattr(song, "name", None), metadata.get("title")),
|
||||
"ARTIST": first_text(getattr(song, "artist", None), metadata.get("artist"), metadata.get("performer")),
|
||||
"ALBUM": first_text(getattr(song, "album", None), metadata.get("album")),
|
||||
"ALBUMARTIST": first_text(getattr(song, "album_artist", None), metadata.get("album_artist")),
|
||||
"TRACKNUMBER": f"{track_number}/{track_total}" if track_number and track_total else track_number,
|
||||
"TRACKTOTAL": track_total,
|
||||
"DISCNUMBER": f"{disc_number}/{disc_total}" if disc_number and disc_total else disc_number,
|
||||
"DISCTOTAL": disc_total,
|
||||
"DATE": _string_tag(metadata.get("release_date") or metadata.get("year") or getattr(song, "year", None)),
|
||||
"RELEASEDATE": _string_tag(metadata.get("release_date")),
|
||||
"GENRE": _first_text(getattr(song, "genre", None), metadata.get("genre")),
|
||||
"COMPOSER": _first_text(metadata.get("composer")),
|
||||
"PERFORMER": _first_text(metadata.get("performer")),
|
||||
"ISRC": _string_tag(getattr(song, "isrc", None) or metadata.get("isrc")),
|
||||
"BARCODE": _string_tag(getattr(song, "upc", None) or metadata.get("upc") or metadata.get("barcode")),
|
||||
"UPC": _string_tag(getattr(song, "upc", None) or metadata.get("upc") or metadata.get("barcode")),
|
||||
"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")),
|
||||
"SOURCE": _first_text(metadata.get("source"), metadata.get("service")),
|
||||
"DATE": string_tag(metadata.get("release_date") or metadata.get("year") or getattr(song, "year", None)),
|
||||
"RELEASEDATE": string_tag(metadata.get("release_date")),
|
||||
"GENRE": first_text(getattr(song, "genre", None), metadata.get("genre")),
|
||||
"COMPOSER": first_text(metadata.get("composer")),
|
||||
"PERFORMER": first_text(metadata.get("performer")),
|
||||
"ISRC": string_tag(getattr(song, "isrc", None) or metadata.get("isrc")),
|
||||
"BARCODE": string_tag(getattr(song, "upc", None) or metadata.get("upc") or metadata.get("barcode")),
|
||||
"UPC": string_tag(getattr(song, "upc", None) or metadata.get("upc") or metadata.get("barcode")),
|
||||
"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")),
|
||||
"SOURCE": first_text(metadata.get("source"), metadata.get("service")),
|
||||
"ENCODEDBY": "Unshackle",
|
||||
"UNSHACKLE_SOURCE_MD5": source_md5,
|
||||
}
|
||||
@@ -126,22 +126,22 @@ def _build_tag_values(song: Any, *, source_md5: str = "") -> dict[str, str]:
|
||||
if config.tag and config.tag_group_name:
|
||||
tags["GROUP"] = config.tag
|
||||
|
||||
service = _first_text(metadata.get("service"), metadata.get("source"))
|
||||
service = first_text(metadata.get("service"), metadata.get("source"))
|
||||
if service:
|
||||
prefix = service.upper().replace(" ", "_").replace("-", "_")
|
||||
if metadata.get("track_id"):
|
||||
tags[f"{prefix}_TRACK_ID"] = _string_tag(metadata.get("track_id"))
|
||||
tags[f"{prefix}_TRACK_ID"] = string_tag(metadata.get("track_id"))
|
||||
if metadata.get("album_id"):
|
||||
tags[f"{prefix}_ALBUM_ID"] = _string_tag(metadata.get("album_id"))
|
||||
tags[f"{prefix}_ALBUM_ID"] = string_tag(metadata.get("album_id"))
|
||||
if metadata.get("track_url"):
|
||||
tags[f"{prefix}_TRACK_URL"] = _string_tag(metadata.get("track_url"))
|
||||
tags[f"{prefix}_TRACK_URL"] = string_tag(metadata.get("track_url"))
|
||||
if metadata.get("album_url"):
|
||||
tags[f"{prefix}_ALBUM_URL"] = _string_tag(metadata.get("album_url"))
|
||||
tags[f"{prefix}_ALBUM_URL"] = string_tag(metadata.get("album_url"))
|
||||
|
||||
return {key: value for key, value in tags.items() if value}
|
||||
|
||||
|
||||
def _write_flac_tags(path: Path, tags: dict[str, str], cover_data: Optional[bytes], mime_type: str) -> None:
|
||||
def write_flac_tags(path: Path, tags: dict[str, str], cover_data: Optional[bytes], mime_type: str) -> None:
|
||||
audio = FLAC(path)
|
||||
for key, value in tags.items():
|
||||
audio[key] = [value]
|
||||
@@ -163,7 +163,7 @@ def _write_flac_tags(path: Path, tags: dict[str, str], cover_data: Optional[byte
|
||||
audio.save()
|
||||
|
||||
|
||||
def _write_mp3_tags(path: Path, tags: dict[str, str], cover_data: Optional[bytes], mime_type: str) -> None:
|
||||
def write_mp3_tags(path: Path, tags: dict[str, str], cover_data: Optional[bytes], mime_type: str) -> None:
|
||||
try:
|
||||
audio = MP3(path)
|
||||
except ID3NoHeaderError:
|
||||
@@ -203,7 +203,7 @@ def _write_mp3_tags(path: Path, tags: dict[str, str], cover_data: Optional[bytes
|
||||
audio.save()
|
||||
|
||||
|
||||
def _write_mp4_tags(path: Path, tags: dict[str, str], cover_data: Optional[bytes], mime_type: str) -> None:
|
||||
def write_mp4_tags(path: Path, tags: dict[str, str], cover_data: Optional[bytes], mime_type: str) -> None:
|
||||
audio = MP4(path)
|
||||
if tags.get("TITLE"):
|
||||
audio["\xa9nam"] = [tags["TITLE"]]
|
||||
@@ -224,10 +224,10 @@ def _write_mp4_tags(path: Path, tags: dict[str, str], cover_data: Optional[bytes
|
||||
if tags.get("COPYRIGHT"):
|
||||
audio["cprt"] = [tags["COPYRIGHT"]]
|
||||
|
||||
track_number, track_total = _split_number_pair(tags.get("TRACKNUMBER", ""))
|
||||
track_number, track_total = split_number_pair(tags.get("TRACKNUMBER", ""))
|
||||
if track_number:
|
||||
audio["trkn"] = [(track_number, track_total or 0)]
|
||||
disc_number, disc_total = _split_number_pair(tags.get("DISCNUMBER", ""))
|
||||
disc_number, disc_total = split_number_pair(tags.get("DISCNUMBER", ""))
|
||||
if disc_number:
|
||||
audio["disk"] = [(disc_number, disc_total or 0)]
|
||||
|
||||
@@ -254,7 +254,7 @@ def _write_mp4_tags(path: Path, tags: dict[str, str], cover_data: Optional[bytes
|
||||
audio.save()
|
||||
|
||||
|
||||
def _download_cover(session: Any, artwork_url: str) -> tuple[Optional[bytes], str]:
|
||||
def download_cover(session: Any, artwork_url: str) -> tuple[Optional[bytes], str]:
|
||||
if not session or not artwork_url:
|
||||
return None, ""
|
||||
try:
|
||||
@@ -264,7 +264,7 @@ def _download_cover(session: Any, artwork_url: str) -> tuple[Optional[bytes], st
|
||||
if not data:
|
||||
return None, ""
|
||||
content_type = str(response.headers.get("Content-Type") or "").split(";")[0].strip().lower()
|
||||
return data, _mime_from_image(data, content_type or "image/jpeg")
|
||||
return data, mime_from_image(data, content_type or "image/jpeg")
|
||||
except Exception as error:
|
||||
log.debug("Music cover download failed for %s: %s", artwork_url, error)
|
||||
return None, ""
|
||||
@@ -275,14 +275,14 @@ def _metadata(song: Any) -> dict[str, Any]:
|
||||
return data if isinstance(data, dict) else {}
|
||||
|
||||
|
||||
def _first_text(*values: Any) -> str:
|
||||
def first_text(*values: Any) -> str:
|
||||
for value in values:
|
||||
if isinstance(value, dict):
|
||||
text = _first_text(value.get("name"), value.get("title"), value.get("display_name"), value.get("value"))
|
||||
text = first_text(value.get("name"), value.get("title"), value.get("display_name"), value.get("value"))
|
||||
if text:
|
||||
return text
|
||||
elif isinstance(value, list):
|
||||
parts = [_first_text(item) for item in value]
|
||||
parts = [first_text(item) for item in value]
|
||||
text = ", ".join(part for part in parts if part)
|
||||
if text:
|
||||
return text
|
||||
@@ -293,7 +293,7 @@ def _first_text(*values: Any) -> str:
|
||||
return ""
|
||||
|
||||
|
||||
def _string_tag(value: Any) -> str:
|
||||
def string_tag(value: Any) -> str:
|
||||
if value in (None, "", [], {}):
|
||||
return ""
|
||||
if isinstance(value, bool):
|
||||
@@ -301,7 +301,7 @@ def _string_tag(value: Any) -> str:
|
||||
return str(value).strip()
|
||||
|
||||
|
||||
def _as_bool(*values: Any) -> bool:
|
||||
def as_bool(*values: Any) -> bool:
|
||||
for value in values:
|
||||
if value in (None, "", [], {}):
|
||||
continue
|
||||
@@ -317,7 +317,7 @@ def _as_bool(*values: Any) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def _mime_from_image(data: bytes, fallback: str = "image/jpeg") -> str:
|
||||
def mime_from_image(data: bytes, fallback: str = "image/jpeg") -> str:
|
||||
if data.startswith(b"\x89PNG\r\n\x1a\n"):
|
||||
return "image/png"
|
||||
if data.startswith(b"\xff\xd8\xff"):
|
||||
@@ -327,7 +327,7 @@ def _mime_from_image(data: bytes, fallback: str = "image/jpeg") -> str:
|
||||
return fallback
|
||||
|
||||
|
||||
def _split_number_pair(value: str) -> tuple[int, int]:
|
||||
def split_number_pair(value: str) -> tuple[int, int]:
|
||||
if not value:
|
||||
return 0, 0
|
||||
first, _, second = str(value).partition("/")
|
||||
|
||||
Reference in New Issue
Block a user