feat(tracks)!: match a language tag to the variant it means

A tag with a region (en-US, es-419) matches only that variant and reports a miss instead of taking another region. A bare tag takes the variant it means (pt -> pt-BR, es -> es-ES) and falls back to any variant only when that one is missing. `orig` prefers the title's own tag, `-sl orig` resolves, forced and SDH subtitles are picked from their own pools, and the track name no longer strips the region from the cached language.

BREAKING CHANGE: -l es-419 no longer selects es-ES, and language_priority, language_tags and muxing.default_language treat a regional tag as exact.
This commit is contained in:
imSp4rky
2026-10-15 12:26:39 -06:00
parent c231114cda
commit a4ce70a53c
26 changed files with 584 additions and 253 deletions
+64 -86
View File
@@ -85,19 +85,19 @@ from unshackle.core.utilities import (
as_requested,
declared_kwargs,
embedded_audio_langs,
excluded_language_tags,
find_font_with_fallbacks,
find_missing_langs,
get_debug_logger,
get_system_fonts,
init_debug_logger,
is_close_match,
is_exact_match,
keep_forced_subtitle,
kind_only_conflict,
log_event,
matched_language_tags,
matching_languages,
missing_required_langs,
original_tag,
partition_exclusions,
plain_subtitle_tags,
resolve_sort_langs,
suggest_font_packages,
time_elapsed_since,
@@ -825,7 +825,7 @@ class dl:
"--exact-lang",
is_flag=True,
default=False,
help="Use exact language matching (no variants). With this flag, -l es-419 matches ONLY es-419, not es-ES or other variants.",
help="A language tag without a region selects only the variant it means and never falls back to another: -l es does not select es-419. A tag with a region, such as es-419, is always exact.",
)
@click.option(
"--proxy",
@@ -2122,8 +2122,11 @@ class dl:
t for t in audio if t.language == language and (codec is None or t.codec == codec)
]
else:
pool = [t for t in audio if codec is None or t.codec == codec]
candidates = Tracks.by_language(pool, [language], per_language=0, exact_match=exact_lang)
# match against every codec at once, so the variant a tag means does not depend on codec
tags = matching_languages(language, [t.language for t in audio], exact_lang)
candidates = [
t for t in audio if str(t.language) in tags and (codec is None or t.codec == codec)
]
if not candidates:
continue
if audio_description:
@@ -2333,16 +2336,13 @@ class dl:
level="INFO", operation="get_tracks", service=self.service, context=tracks_info
)
# strip SDH subs to non-SDH if no equivalent same-lang non-SDH is available
# uses a loose check, e.g, wont strip en-US SDH sub if a non-SDH en-GB is available
# Check if automatic SDH stripping is enabled in config
# a plain track covers an SDH track only when it is the same variant, as -sl selects them,
# so en-US SDH is stripped next to a plain en-GB: -sl en-US would otherwise keep only the SDH
if config.subtitle.get("strip_sdh", True):
plain_langs = [x.language for x in title.tracks.subtitles if not x.sdh and not x.forced]
for subtitle in title.tracks.subtitles:
if subtitle.sdh and not any(
is_close_match(subtitle.language, [x.language])
for x in title.tracks.subtitles
if not x.sdh and not x.forced
):
if subtitle.sdh and not matching_languages(subtitle.language, plain_langs, exact=True):
plain_langs.append(subtitle.language)
non_sdh_sub = deepcopy(subtitle)
non_sdh_sub.id += "_stripped"
non_sdh_sub.sdh = False
@@ -2377,16 +2377,20 @@ class dl:
subtitle_priority = config.subtitle.get("language_priority") or []
title.tracks.sort_videos(
by_language=resolve_sort_langs(v_lang or lang, title.language),
by_language=resolve_sort_langs(v_lang or lang, title.language, exact=exact_lang),
exact_match=exact_lang,
)
title.tracks.sort_audio(
by_language=resolve_sort_langs([*audio_priority, *(a_lang or lang)], title.language),
by_language=resolve_sort_langs(
[*audio_priority, *(a_lang or lang)], title.language, exact=exact_lang
),
codec_priority=config.audio.get("codec_priority"),
exact_match=exact_lang,
)
title.tracks.sort_subtitles(
by_language=resolve_sort_langs([*subtitle_priority, *(s_lang or [])], title.language),
by_language=resolve_sort_langs(
[*subtitle_priority, *(s_lang or [])], title.language, exact=exact_lang
),
type_priority=config.subtitle.get("type_priority"),
group_by=config.subtitle.get("group_by"),
exact_match=exact_lang,
@@ -2468,22 +2472,10 @@ class dl:
title.tracks.chapters = []
with console.status("Selecting tracks...", spinner="dots"):
def resolve_excludes(excludes: list[str], _title: Title_T = title) -> list[str]:
"""Change 'orig' to this title's language. An 'orig' with no language excludes nothing."""
resolved: list[str] = []
for token in excludes:
value = str(_title.language) if token == "orig" else token
if token == "orig" and not _title.language:
continue
if value not in resolved:
resolved.append(value)
return resolved
video_excl_r = resolve_excludes(video_excl)
audio_excl_r = resolve_excludes(audio_excl)
s_excl_r = resolve_excludes(s_lang_excl)
fsl_excl_r = resolve_excludes(fsl_excl)
video_excl_r = resolve_sort_langs(video_excl, title.language, exact=exact_lang)
audio_excl_r = resolve_sort_langs(audio_excl, title.language, exact=exact_lang)
s_excl_r = resolve_sort_langs(s_lang_excl, title.language, exact=exact_lang)
fsl_excl_r = resolve_sort_langs(fsl_excl, title.language, exact=exact_lang)
if isinstance(title, (Movie, Episode)):
if keep_videos and vcodec:
@@ -2531,8 +2523,8 @@ class dl:
sys.exit(1)
if keep_videos and video_excl_r:
drop = excluded_language_tags(
video_excl_r, [t.language for t in title.tracks.videos], exact_lang
drop = matched_language_tags(
video_excl_r, [t.language for t in title.tracks.videos], exact_lang, every_variant=True
)
title.tracks.select_video(lambda x: str(x.language) not in drop)
if not title.tracks.videos:
@@ -2545,22 +2537,15 @@ class dl:
"best" in effective_video_lang or "all" in effective_video_lang or len(video_languages) > 1
)
if keep_videos and video_languages and "all" not in video_languages:
processed_video_lang = []
processed_video_lang = resolve_sort_langs(video_languages, title.language, exact=exact_lang)
v_orig_token: Optional[str] = None
for language in video_languages:
if language == "orig":
if title.language:
orig_lang = str(title.language)
v_orig_token = orig_lang
if orig_lang not in processed_video_lang:
processed_video_lang.append(orig_lang)
else:
self.log.warning(
"Original language not available for title, skipping 'orig' selection for video"
)
if "orig" in video_languages:
if title.language:
v_orig_token = original_tag(title.language, exact_lang)
else:
if language not in processed_video_lang:
processed_video_lang.append(language)
self.log.warning(
"Original language not available for title, skipping 'orig' selection for video"
)
if v_orig_token in video_languages:
v_orig_token = None
missing_v_langs = find_missing_langs(
@@ -2810,21 +2795,19 @@ class dl:
self.log.error(msg_detail)
sys.exit(1)
fsl = [t for t in forced_s_lang if t != "orig"]
if "orig" in forced_s_lang and title.language:
fsl.append(str(title.language))
fsl = resolve_sort_langs(forced_s_lang, title.language, exact=exact_lang)
if keep_subtitles and s_excl_r:
# applies to forced subs too: an excluded language is unwanted in any form
drop = excluded_language_tags(
s_excl_r, [t.language for t in title.tracks.subtitles], exact_lang
drop = matched_language_tags(
s_excl_r, [t.language for t in title.tracks.subtitles], exact_lang, every_variant=True
)
title.tracks.select_subtitles(lambda x: str(x.language) not in drop)
if keep_subtitles and s_lang and "all" not in s_lang:
match_func = is_exact_match if exact_lang else is_close_match
s_lang = resolve_sort_langs(s_lang, title.language, exact=exact_lang)
# the pool selection draws from: forced tracks count only when -fs keeps them
missing_langs = find_missing_langs(
s_lang,
[sub.language for sub in title.tracks.subtitles],
[sub.language for sub in title.tracks.subtitles if forced_subs or not sub.forced],
exact=exact_lang,
)
if missing_langs:
@@ -2840,21 +2823,21 @@ class dl:
self.log.warning(
f"{missing_str} not found in subtitle tracks, continuing without subtitles"
)
title.tracks.select_subtitles(
lambda x: (
x.forced and keep_forced_subtitle(x.forced, x.language, fsl, exact_lang)
)
fsl_tags = matched_language_tags(
fsl, [x.language for x in title.tracks.subtitles if x.forced], exact_lang
)
title.tracks.select_subtitles(lambda x: x.forced and str(x.language) in fsl_tags)
else:
self.log.error(missing_str + " not found in subtitle tracks")
sys.exit(1)
if s_lang and title.tracks.subtitles:
plain_tags = plain_subtitle_tags(s_lang, title.tracks.subtitles, exact_lang)
forced_tags = matched_language_tags(
[*s_lang, *fsl], [x.language for x in title.tracks.subtitles if x.forced], exact_lang
)
title.tracks.select_subtitles(
lambda x: (
match_func(x.language, s_lang)
or bool(x.forced and fsl and match_func(x.language, fsl))
)
lambda x: str(x.language) in (forced_tags if x.forced else plain_tags)
)
if not title.tracks.subtitles and not best_available:
self.log.error(f"There's no {s_lang} Subtitle Track...")
@@ -2863,9 +2846,10 @@ class dl:
if keep_subtitles:
# fsl, not forced_s_lang: unresolvable orig must keep all forced, not drop them
if fsl:
title.tracks.select_subtitles(
lambda x: keep_forced_subtitle(x.forced, x.language, fsl, exact_lang)
fsl_tags = matched_language_tags(
fsl, [x.language for x in title.tracks.subtitles if x.forced], exact_lang
)
title.tracks.select_subtitles(lambda x: not x.forced or str(x.language) in fsl_tags)
if not any(x.forced for x in title.tracks.subtitles):
self.log.warning(
f"No forced subtitle tracks matched --forced-s-lang ({', '.join(forced_s_lang)})"
@@ -2873,8 +2857,11 @@ class dl:
elif not forced_subs:
title.tracks.select_subtitles(lambda x: not x.forced)
if fsl_excl_r:
drop = excluded_language_tags(
fsl_excl_r, [t.language for t in title.tracks.subtitles if t.forced], exact_lang
drop = matched_language_tags(
fsl_excl_r,
[t.language for t in title.tracks.subtitles if t.forced],
exact_lang,
every_variant=True,
)
title.tracks.select_subtitles(lambda x: not (x.forced and str(x.language) in drop))
if forced_subs_only:
@@ -2928,8 +2915,8 @@ class dl:
self.log.error(f"No Audio Track in {abitrate_min}-{abitrate_max}kbps range...")
sys.exit(1)
if audio_excl_r:
drop = excluded_language_tags(
audio_excl_r, [t.language for t in title.tracks.audio], exact_lang
drop = matched_language_tags(
audio_excl_r, [t.language for t in title.tracks.audio], exact_lang, every_variant=True
)
title.tracks.select_audio(lambda x: str(x.language) not in drop)
if not title.tracks.audio:
@@ -2937,22 +2924,13 @@ class dl:
sys.exit(1)
audio_languages = a_lang or lang
if audio_languages:
processed_lang = []
processed_lang = resolve_sort_langs(audio_languages, title.language, exact=exact_lang)
a_orig_token: Optional[str] = None
for language in audio_languages:
if language == "orig":
if title.language:
orig_lang = str(title.language)
a_orig_token = orig_lang
if orig_lang not in processed_lang:
processed_lang.append(orig_lang)
else:
self.log.warning(
"Original language not available for title, skipping 'orig' selection"
)
if "orig" in audio_languages:
if title.language:
a_orig_token = original_tag(title.language, exact_lang)
else:
if language not in processed_lang:
processed_lang.append(language)
self.log.warning("Original language not available for title, skipping 'orig' selection")
if a_orig_token in audio_languages:
a_orig_token = None
+4 -11
View File
@@ -36,7 +36,7 @@ from unshackle.core.session import utf8_text
from unshackle.core.titles import Episode, Movie, Song, Title_T
from unshackle.core.titles.music import SONG_FIELDS
from unshackle.core.tracks import Audio, Subtitle, Tracks, Video
from unshackle.core.utilities import declared_kwargs, kind_only_conflict
from unshackle.core.utilities import declared_kwargs, kind_only_conflict, original_tag
from unshackle.core.utils.click_types import AUDIO_CODEC_LIST, SUBTITLE_CODEC, VIDEO_CODEC_LIST
from unshackle.core.utils.collections import ci_get
from unshackle.core.utils.redact import REDACTED, URL_USERINFO_RE, redact_all, redact_secrets, redact_text
@@ -1429,20 +1429,13 @@ def serialize_video_track(track: Video, include_url: bool = False) -> Dict[str,
def original_audio_ids(tracks: List[Audio], title: Title_T) -> set:
"""Return the ids of the audio tracks 'orig' resolves to, empty when the title has no language.
This defers to Tracks.by_language so the flag agrees with the downloader. It asks
exact mode first because CLDR rates a base tag and its paradigm regional variant as
the same language, and only the RFC 4647 preference picks one ('en' over 'en-US'
when both exist, 'pt-BR' over 'pt-PT' for a 'pt' title). The fuzzy fallback then
catches the non-paradigm regionals exact mode drops, such as an 'es' title that
carries only 'es-419'.
This defers to Tracks.by_language through original_tag, as 'orig' does, so the flag agrees
with the downloader: the title's own variant first, else its close regional forms.
"""
language = getattr(title, "language", None)
if not language:
return set()
matches = Tracks.by_language(tracks, [str(language)], exact_match=True) or Tracks.by_language(
tracks, [str(language)]
)
return {t.id for t in matches}
return {t.id for t in Tracks.by_language(tracks, [original_tag(language)])}
def serialize_audio_track(track: Audio, include_url: bool = False, is_original: bool = False) -> Dict[str, Any]:
+1 -1
View File
@@ -909,7 +909,7 @@ async def download(request: web.Request) -> web.Response:
description: Languages wanted for forced subtitles, implies forced_subs (a '-' prefix excludes) (default - [])
exact_lang:
type: boolean
description: Use exact language matching (no variants) (default - false)
description: A language tag without a region never falls back to another variant; a tag with a region is always exact (default - false)
sub_format:
type: string
description: Output subtitle format such as SRT or VTT, or "original" to keep the source format (default - None)
+2 -2
View File
@@ -508,9 +508,9 @@ class Track:
self.extra: Any = extra or {} # allow anything for extra, but default to a dict
if self.name is None:
lang = Language.get(self.language)
lang = self.language
if (lang.language or "").lower() == (lang.territory or "").lower():
lang.territory = None
lang = lang.update_dict({"territory": None})
reduced = lang.simplify_script()
extra_parts = []
if reduced.script is not None:
+38 -29
View File
@@ -30,6 +30,7 @@ from unshackle.core.utilities import (
is_close_match,
log_event,
matching_languages,
original_tag,
sanitize_filename,
valid_language,
)
@@ -270,12 +271,14 @@ class Tracks:
self.videos.sort(key=lambda x: (x.height or 0, float(x.bitrate or 0.0)), reverse=True)
for language in reversed(by_language or []):
if str(language) in ("all", "best"):
language = next((x.language for x in self.videos if x.is_original_lang), "")
language = self._original_language(self.videos, exact_match)
if not language:
continue
wanted = matching_languages(language, [x.language for x in self.videos], exact_match)
langs = [x.language for x in self.videos]
wanted = matching_languages(language, langs, exact_match)
related = matching_languages(language, langs, exact_match, every_variant=True)
self.videos.sort(key=lambda x: str(x.language))
self.videos.sort(key=lambda x: str(x.language) not in wanted)
self.videos.sort(key=lambda x: (str(x.language) not in related, str(x.language) not in wanted))
def sort_audio(
self,
@@ -298,11 +301,13 @@ class Tracks:
self.audio.sort(key=lambda x: x.descriptive)
for language in reversed(by_language or []):
if str(language) in ("all", "best"):
language = next((x.language for x in self.audio if x.is_original_lang), "")
language = self._original_language(self.audio, exact_match)
if not language:
continue
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)
langs = [x.language for x in self.audio]
wanted = matching_languages(language, langs, exact_match)
related = matching_languages(language, langs, exact_match, every_variant=True)
self.audio.sort(key=lambda x: (str(x.language) not in related, str(x.language) not in wanted))
def sort_subtitles(
self,
@@ -365,11 +370,13 @@ class Tracks:
by_type()
for language in reversed(by_language or []):
if str(language) in ("all", "best"):
language = next((x.language for x in self.subtitles if x.is_original_lang), "")
language = self._original_language(self.subtitles, exact_match)
if not language:
continue
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)
langs = [x.language for x in self.subtitles]
wanted = matching_languages(language, langs, exact_match)
related = matching_languages(language, langs, exact_match, every_variant=True)
self.subtitles.sort(key=lambda x: (str(x.language) not in related, str(x.language) not in wanted))
def select_video(self, x: Callable[[Video], bool]) -> None:
self.videos = list(filter(x, self.videos))
@@ -496,6 +503,23 @@ class Tracks:
selected.append(track)
return selected
@staticmethod
def _original_language(tracks: Sequence[AnyTrack], exact: bool) -> str:
"""The language "all" and "best" sort first: the original-language track's, through original_tag."""
language = next((x.language for x in tracks if x.is_original_lang), None)
return original_tag(language, exact) if language else ""
@staticmethod
def first_match_index(tracks: Sequence[AnyTrack], language: Optional[str]) -> Optional[int]:
"""The index of the first track that `language` asks for, matched against every track at once.
Matching the whole list lets the RFC 4647 string preference pick en-US over en.
"""
if not language:
return None
wanted = matching_languages(language, [t.language for t in tracks])
return next((idx for idx, t in enumerate(tracks) if str(t.language) in wanted), None)
@property
def sample_base(self) -> float:
"""The earliest ``sample_start`` of the video and audio tracks, which a sample mux uses as time zero."""
@@ -769,26 +793,11 @@ class Tracks:
preferred_audio_lang = valid_language(default_language.get("audio"))
preferred_subtitle_lang = valid_language(default_language.get("subtitle"))
preferred_video_idx: Optional[int] = None
if preferred_video_lang:
preferred_video_idx = next(
(idx for idx, v in enumerate(self.videos) if is_close_match(v.language, [preferred_video_lang])),
None,
)
preferred_audio_idx: Optional[int] = None
if preferred_audio_lang:
preferred_audio_idx = next(
(idx for idx, a in enumerate(self.audio) if is_close_match(a.language, [preferred_audio_lang])),
None,
)
preferred_subtitle_idx: Optional[int] = None
if preferred_subtitle_lang and not skip_subtitles:
preferred_subtitle_idx = next(
(idx for idx, s in enumerate(self.subtitles) if is_close_match(s.language, [preferred_subtitle_lang])),
None,
)
preferred_video_idx = self.first_match_index(self.videos, preferred_video_lang)
preferred_audio_idx = self.first_match_index(self.audio, preferred_audio_lang)
preferred_subtitle_idx = (
None if skip_subtitles else self.first_match_index(self.subtitles, preferred_subtitle_lang)
)
for i, vt in enumerate(self.videos):
if not vt.path or not vt.path.exists():
+65 -39
View File
@@ -205,34 +205,36 @@ def partition_exclusions(tokens: Optional[Sequence[str]]) -> tuple[list[str], li
return includes, excludes
def excluded_language_tags(
excludes: Sequence[str],
def matched_language_tags(
tokens: Sequence[str],
available: Sequence[Union[str, Language, None]],
exact: bool = False,
*,
every_variant: bool = False,
) -> set[str]:
"""
The language tags out of `available` that the exclusion tokens remove.
The language tags out of `available` that any of the tokens asks for.
Matches through matching_languages so an exclusion drops exactly the tracks the same
token would select, including its exact-mode string preference. Untagged tracks are
never excluded.
Matches through matching_languages. An exclusion passes every_variant, so "-es" drops
every Spanish track. Untagged tracks never match.
"""
return {tag for token in excludes for tag in matching_languages(token, available, exact)}
return {tag for token in tokens for tag in matching_languages(token, available, exact, every_variant=every_variant)}
def keep_forced_subtitle(
forced: bool,
language: Union[str, Language],
forced_s_lang: Sequence[str],
exact: bool = False,
) -> bool:
"""The -fsl filter: non-forced tracks always pass, forced tracks only when they match forced_s_lang."""
if not forced:
return True
if not forced_s_lang:
return False
match_func = is_exact_match if exact else is_close_match
return match_func(language, forced_s_lang)
def plain_subtitle_tags(tokens: Sequence[str], subtitles: Sequence[Any], exact: bool = False) -> set[str]:
"""
The non-forced subtitle tags the -sl tokens select.
Each token is matched against the plain tracks before the SDH ones, so an SDH track cannot win
the string-equal preference over the plain variant: -sl en with plain en-US and SDH en takes
en-US. An SDH track then joins when it is the same variant as a chosen tag.
"""
plain = [x.language for x in subtitles if not x.forced and not x.sdh]
sdh = [x.language for x in subtitles if not x.forced and x.sdh]
tags: set[str] = set()
for token in tokens:
tags |= matching_languages(token, plain, exact) or matching_languages(token, sdh, exact)
return tags | {str(lang) for lang in sdh if tags and matching_languages(lang, list(tags), exact=True)}
def kind_only_conflict(params: Mapping[str, Any]) -> Optional[tuple[str, str]]:
@@ -296,9 +298,8 @@ def find_missing_langs(
exact: bool = False,
) -> list[str]:
"""Return the requested language tokens that match no available language."""
match_func = is_exact_match if exact else is_close_match
skip = {"all", "best", "orig"}
return [tok for tok in requested if tok not in skip and not match_func(tok, available)]
return [tok for tok in requested if tok not in skip and not matching_languages(tok, available, exact)]
def missing_required_langs(
@@ -315,7 +316,7 @@ def missing_required_langs(
token ("-fr") asks for a language to be absent, so it is never a required language.
"""
wanted, _ = partition_exclusions(list(required))
return find_missing_langs(resolve_sort_langs(wanted, original), available, exact=exact)
return find_missing_langs(resolve_sort_langs(wanted, original, exact=exact), available, exact=exact)
def as_requested(tokens: Sequence[str], orig_token: Optional[str]) -> str:
@@ -327,40 +328,65 @@ def matching_languages(
language: Union[str, Language],
available: Sequence[Union[str, Language, None]],
exact: bool = False,
*,
every_variant: 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 rating only when no such tag is present (for example, zh matches
cmn).
A tag asks for the variant it means. A tag with a region (en-US, es-419) gets only that
variant. A bare tag gets the variant it implies (pt means pt-BR, es means es-ES) and, when
the title has none, every regional form, unless exact or the caller sets every_variant,
which always returns every form. A ServiceTag falls back the same way, from its own tag. The meant variant follows RFC 4647 Lookup: the string-equal
tag, else CLDR distance 0 (zh matches cmn, en-US matches en). Distance alone cannot do it,
because it rates a base language and its paradigm variant (en/en-US) the same.
"""
tags = {str(x) for x in available if x}
try:
want = Language.get(str(language)).to_tag().casefold()
requested = Language.get(str(language))
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])}
want = requested.to_tag().casefold()
variants: set[str] = set()
if not exact and (isinstance(language, ServiceTag) or not requested.territory):
variants = {tag for tag in tags if is_close_match(language, [tag])}
if every_variant:
return variants
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])}
return string_equal or {tag for tag in tags if is_exact_match(language, [tag])} or variants
def resolve_sort_langs(tokens: Sequence[str], original: Optional[Union[str, Language]] = None) -> list[str]:
class ServiceTag(str):
"""A language the service supplied, such as the title language "orig" becomes.
matching_languages takes its own variant first and falls back to the close regional forms,
because the service, not the user, chose its region.
"""
Prepare language tokens for a Tracks.sort_* by_language argument.
"orig" becomes the title language. This function drops it when the title has none.
"all" and "best" pass through, because the sort methods find them among the tracks. The
result keeps the first position of each language and drops later repeats.
def original_tag(language: Union[str, Language], exact: bool = False) -> str:
"""The tag to match a service-supplied language with: a ServiceTag, or the plain tag in exact mode."""
return str(language) if exact else ServiceTag(str(language))
def resolve_sort_langs(
tokens: Sequence[str], original: Optional[Union[str, Language]] = None, *, exact: bool = False
) -> list[str]:
"""
Resolve language tokens for selection, exclusion and the Tracks.sort_* by_language argument.
"orig" becomes the title language through original_tag. This function drops it when the
title has none. "all" and "best" pass through, because the sort methods find them among
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:
if token != "orig":
language = str(token)
elif original:
language = original_tag(original, exact)
else:
continue
if language not in resolved:
resolved.append(language)
+3 -8
View File
@@ -7,9 +7,8 @@ from collections.abc import Mapping as MappingABC
from typing import Any, Mapping, Optional, Sequence
from langcodes import Language
from langcodes.tag_parser import LanguageTagError
from unshackle.core.utilities import is_close_match
from unshackle.core.utilities import matching_languages, valid_language
log = logging.getLogger(__name__)
@@ -116,13 +115,9 @@ def _as_list(value: Any) -> list[Any]:
def _matches(lang: Any, languages: Sequence[Language]) -> bool:
"""Return True when the rule language closely matches one of the track languages.
"""Return True when the rule language matches one of the track languages, as a -l token would.
A rule value that is not a valid language tag counts as no match. The filename is built
after the mux, so a typo in the config must not discard a finished download.
"""
try:
return is_close_match(lang, list(languages))
except LanguageTagError as e:
log.warning("Language tag rule value %r is not a valid language tag, treating as no match: %s", lang, e)
return False
return bool(valid_language(lang) and matching_languages(lang, languages))