feat(tracks): add language_priority to sort preferred languages first

subtitle.language_priority and audio.language_priority prepend to the CLI
languages, so the named languages sort first and nothing is filtered.
--exact-lang now applies to the sorts too, through matching_languages, which
follows the same RFC 4647 rule as Tracks.by_language and ignores invalid tags.
This commit is contained in:
imSp4rky
2026-08-03 10:15:05 -06:00
parent 4e1ccf3230
commit a6997f6bca
10 changed files with 277 additions and 36 deletions
+16 -27
View File
@@ -83,6 +83,7 @@ from unshackle.core.utilities import (
is_exact_match,
keep_forced_subtitle,
log_event,
resolve_sort_langs,
suggest_font_packages,
time_elapsed_since,
)
@@ -1859,8 +1860,12 @@ class dl:
song.tracks.add(service.get_tracks(song), warn_only=True)
song.tracks.chapters = service.get_chapters(song)
song.tracks.sort_audio(
by_language=a_lang or lang,
by_language=resolve_sort_langs(
[*(config.audio.get("language_priority") or []), *(a_lang or lang)],
song.language,
),
codec_priority=config.audio.get("codec_priority"),
exact_match=exact_lang,
)
select_music_audio(song)
if not song.tracks.audio:
@@ -2389,39 +2394,23 @@ class dl:
)
with console.status("Sorting tracks by language and bitrate...", spinner="dots"):
video_sort_lang = v_lang or lang
processed_video_sort_lang = []
for language in video_sort_lang:
if language == "orig":
if title.language:
orig_lang = str(title.language)
if orig_lang not in processed_video_sort_lang:
processed_video_sort_lang.append(orig_lang)
else:
if language not in processed_video_sort_lang:
processed_video_sort_lang.append(language)
audio_priority = config.audio.get("language_priority") or []
subtitle_priority = config.subtitle.get("language_priority") or []
audio_sort_lang = a_lang or lang
processed_audio_sort_lang = []
for language in audio_sort_lang:
if language == "orig":
if title.language:
orig_lang = str(title.language)
if orig_lang not in processed_audio_sort_lang:
processed_audio_sort_lang.append(orig_lang)
else:
if language not in processed_audio_sort_lang:
processed_audio_sort_lang.append(language)
title.tracks.sort_videos(by_language=processed_video_sort_lang)
title.tracks.sort_videos(
by_language=resolve_sort_langs(v_lang or lang, title.language),
exact_match=exact_lang,
)
title.tracks.sort_audio(
by_language=processed_audio_sort_lang,
by_language=resolve_sort_langs([*audio_priority, *(a_lang or lang)], title.language),
codec_priority=config.audio.get("codec_priority"),
exact_match=exact_lang,
)
title.tracks.sort_subtitles(
by_language=s_lang,
by_language=resolve_sort_langs([*subtitle_priority, *s_lang], title.language),
type_priority=config.subtitle.get("type_priority"),
group_by=config.subtitle.get("group_by"),
exact_match=exact_lang,
)
if list_:
+15 -5
View File
@@ -23,7 +23,7 @@ from unshackle.core.tracks.chapters import Chapter, Chapters
from unshackle.core.tracks.subtitle import Subtitle
from unshackle.core.tracks.track import Track
from unshackle.core.tracks.video import Video
from unshackle.core.utilities import is_close_match, log_event, sanitize_filename
from unshackle.core.utilities import is_close_match, log_event, matching_languages, sanitize_filename
from unshackle.core.utils.collections import as_list, flatten
@@ -243,7 +243,9 @@ class Tracks:
if duplicates:
log.debug(f" - Found and skipped {duplicates} duplicate tracks...")
def sort_videos(self, by_language: Optional[Sequence[Union[str, Language]]] = None) -> None:
def sort_videos(
self, by_language: Optional[Sequence[Union[str, Language]]] = None, exact_match: bool = False
) -> None:
"""Sort video tracks by resolution then bitrate, and optionally language."""
if not self.videos:
return
@@ -255,13 +257,15 @@ class Tracks:
language = next((x.language for x in self.videos if x.is_original_lang), "")
if not language:
continue
wanted = matching_languages(language, [x.language for x in self.videos], exact_match)
self.videos.sort(key=lambda x: str(x.language))
self.videos.sort(key=lambda x: not is_close_match(language, [x.language]))
self.videos.sort(key=lambda x: str(x.language) not in wanted)
def sort_audio(
self,
by_language: Optional[Sequence[Union[str, Language]]] = None,
codec_priority: Optional[Sequence[str]] = None,
exact_match: bool = False,
) -> None:
"""Sort audio tracks by bitrate, codec priority, Atmos, descriptive, and optionally language."""
if not self.audio:
@@ -283,13 +287,15 @@ class Tracks:
language = next((x.language for x in self.audio if x.is_original_lang), "")
if not language:
continue
self.audio.sort(key=lambda x: not is_close_match(language, [x.language]))
wanted = matching_languages(language, [x.language for x in self.audio], exact_match)
self.audio.sort(key=lambda x: str(x.language) not in wanted)
def sort_subtitles(
self,
by_language: Optional[Sequence[Union[str, Language]]] = None,
type_priority: Optional[Sequence[str]] = None,
group_by: Optional[str] = None,
exact_match: bool = False,
) -> None:
"""
Sort subtitle tracks by various track attributes to a common P2P standard.
@@ -313,6 +319,9 @@ class Tracks:
then every normal, then every SDH, each block ascending by language. "language"
groups by language instead, so Finnish sits next to Finnish SDH, with the Type
Order applied inside each language.
exact_match makes a by_language entry sort only its own tag. By default "en" also
sorts "en-US" and "en-GB".
"""
if not self.subtitles:
return
@@ -346,7 +355,8 @@ class Tracks:
language = next((x.language for x in self.subtitles if x.is_original_lang), "")
if not language:
continue
self.subtitles.sort(key=lambda x: is_close_match(language, [x.language]), reverse=True)
wanted = matching_languages(language, [x.language for x in self.subtitles], exact_match)
self.subtitles.sort(key=lambda x: str(x.language) in wanted, reverse=True)
def select_video(self, x: Callable[[Video], bool]) -> None:
self.videos = list(filter(x, self.videos))
+44
View File
@@ -25,6 +25,7 @@ import pycountry
from construct import ValidationError
from fontTools import ttLib
from langcodes import Language, closest_match
from langcodes.tag_parser import LanguageTagError
from pymp4.parser import Box
from unidecode import unidecode
@@ -195,6 +196,49 @@ def as_requested(tokens: Sequence[str], orig_token: Optional[str]) -> str:
return ", ".join("orig" if tok == orig_token else tok for tok in tokens)
def matching_languages(
language: Union[str, Language],
available: Sequence[Union[str, Language, None]],
exact: bool = False,
) -> set[str]:
"""
The languages out of `available` that `language` asks for, by the rules Tracks.by_language uses.
In exact mode CLDR tag distance is not sufficient on its own: it rates a base language and
its "paradigm" regional variant as the same language (distance 0 for en/en-US, pt/pt-BR), so
it cannot separate en-US from en. Follow RFC 4647 Lookup: prefer the string-equal tag, and
fall back to the distance match only when no such tag is present (e.g. zh matches cmn).
"""
tags = {str(x) for x in available if x}
try:
want = Language.get(str(language)).to_tag().casefold()
except LanguageTagError:
# e.g. a config typo in language_priority; an unparseable tag matches nothing
return set()
if not exact:
return {tag for tag in tags if is_close_match(language, [tag])}
string_equal = {tag for tag in tags if Language.get(tag).to_tag().casefold() == want}
return string_equal or {tag for tag in tags if is_exact_match(language, [tag])}
def resolve_sort_langs(tokens: Sequence[str], original: Optional[Union[str, Language]] = None) -> list[str]:
"""
Prepare language tokens for a Tracks.sort_* by_language argument.
"orig" becomes the title language, or is dropped when the title has none. "all" and
"best" pass through, because the sort methods resolve them against the tracks. The
result keeps the first position of each language and drops later repeats.
"""
resolved: list[str] = []
for token in tokens:
language = str(original) if token == "orig" else str(token)
if token == "orig" and not original:
continue
if language not in resolved:
resolved.append(language)
return resolved
def get_boxes(data: bytes, box_type: bytes, as_bytes: bool = False) -> Box: # type: ignore
"""
Scan a byte array for a wanted MP4/ISOBMFF box, then parse and yield each find.