forked from kenzuya/unshackle
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:
@@ -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]:
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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
@@ -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)
|
||||
|
||||
@@ -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))
|
||||
|
||||
Reference in New Issue
Block a user