fix(naming): correct language tag rule matching and add state conditions

Rules took only a scalar, so the documented list syntax raised LanguageTagError after the mux. Normalise every condition, treat an invalid tag as no match, guard the surrounding post-mux config reads, and let a rule match dual, multi and dubbed so a release can carry its own tag.
This commit is contained in:
imSp4rky
2026-09-11 20:00:08 -06:00
parent f43b90d6b6
commit c8a674d85d
9 changed files with 207 additions and 18 deletions
+5 -1
View File
@@ -258,7 +258,11 @@ class Episode(Title):
name += f" {self.folder_season()}"
return sanitize_filename(name, " ")
formatter = TemplateFormatter(config.output_template["series"])
template = config.output_template.get("series")
if not template:
return sanitize_filename(str(self), " ")
formatter = TemplateFormatter(template)
context = self.build_template_context(media_info, show_service)
return formatter.format(context)
+5 -1
View File
@@ -76,7 +76,11 @@ class Movie(Title):
name += f" ({self.year})"
return sanitize_filename(name, " ")
formatter = TemplateFormatter(config.output_template["movies"])
template = config.output_template.get("movies")
if not template:
return sanitize_filename(str(self), " ")
formatter = TemplateFormatter(template)
context = self.build_template_context(media_info, show_service)
return formatter.format(context)
+4 -2
View File
@@ -213,13 +213,15 @@ class Title:
if original_lang_tag and original_lang_tag not in audio_lang_bases:
context["dubbed"] = "DUBBED"
lang_tag_rules = config.language_tags.get("rules") if config.language_tags else None
language_tags = config.language_tags if isinstance(config.language_tags, dict) else {}
lang_tag_rules = language_tags.get("rules")
if lang_tag_rules and self.tracks:
from unshackle.core.utils.language_tags import evaluate_language_tag
audio_langs = [a.language for a in self.tracks.audio]
sub_langs = [s.language for s in self.tracks.subtitles]
context["lang_tag"] = evaluate_language_tag(lang_tag_rules, audio_langs, sub_langs)
states = {name: bool(context[name]) for name in ("dual", "multi", "dubbed")}
context["lang_tag"] = evaluate_language_tag(lang_tag_rules, audio_langs, sub_langs, states)
if config.tag_rules:
from unshackle.core.utils.tag_rules import evaluate_tag_rules
+11 -4
View File
@@ -26,7 +26,13 @@ from unshackle.core.tracks.chapters import Chapter, Chapters
from unshackle.core.tracks.subtitle import Subtitle
from unshackle.core.tracks.track import Track, has_dts_uhd_sample_entry, strip_duplicate_init_boxes
from unshackle.core.tracks.video import Video
from unshackle.core.utilities import is_close_match, log_event, matching_languages, sanitize_filename
from unshackle.core.utilities import (
is_close_match,
log_event,
matching_languages,
sanitize_filename,
valid_language,
)
from unshackle.core.utils.collections import as_list, flatten
MP4BOX_PROGRESS = re.compile(r"\((\d{1,3})/100\)")
@@ -727,9 +733,10 @@ class Tracks:
cl.extend(["--title", title])
default_language = config.muxing.get("default_language") or {}
preferred_video_lang = default_language.get("video")
preferred_audio_lang = default_language.get("audio")
preferred_subtitle_lang = default_language.get("subtitle")
# mux() runs after every track is downloaded, so a typo here must not discard the title
preferred_video_lang = valid_language(default_language.get("video"))
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:
+12
View File
@@ -153,6 +153,18 @@ def is_close_match(language: Union[str, Language], languages: Sequence[Union[str
return closest_match(language, list(map(str, languages)))[1] <= LANGUAGE_MAX_DISTANCE
def valid_language(language: Any) -> Optional[str]:
"""Return the language tag as text, or None when it is not a valid tag."""
if not language:
return None
try:
Language.get(str(language))
except LanguageTagError:
logging.getLogger("utilities").warning("%r is not a valid language tag, ignoring it", language)
return None
return str(language)
def is_exact_match(language: Union[str, Language], languages: Sequence[Union[str, Language, None]]) -> bool:
"""Examine whether a language exactly matches any of the given languages."""
languages = [x for x in languages if x]
+57 -8
View File
@@ -3,19 +3,26 @@
from __future__ import annotations
import logging
from typing import Any, Sequence
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
log = logging.getLogger(__name__)
# Conditions that test a filename variable of the same name rather than a language.
STATE_CONDITIONS = ("dual", "multi", "dubbed")
LANGUAGE_CONDITIONS = ("audio", "subs_contain", "subs_contain_all")
def evaluate_language_tag(
rules: list[dict[str, Any]],
audio_languages: Sequence[Language],
subtitle_languages: Sequence[Language],
states: Optional[Mapping[str, bool]] = None,
) -> str:
"""Evaluate language tag rules against selected tracks.
@@ -26,17 +33,27 @@ def evaluate_language_tag(
rules: List of rule dicts from config, each with conditions and a ``tag``.
audio_languages: Languages of the selected audio tracks.
subtitle_languages: Languages of the selected subtitle tracks.
states: Whether each of ``dual``, ``multi`` and ``dubbed`` is set for this release,
the same state as the filename variable of that name.
Returns:
The tag string from the first rule that matches, or ``""`` if none match.
"""
if not isinstance(rules, list):
log.warning("Language tag rules must be a list of rules, ignoring: %r", rules)
return ""
for rule in rules:
if not isinstance(rule, MappingABC):
log.warning("Language tag rule must be a mapping of conditions and a 'tag', skipping: %r", rule)
continue
tag = rule.get("tag")
if not tag:
log.warning("Language tag rule missing 'tag' field, skipping: %s", rule)
continue
if rule_matches(rule, audio_languages, subtitle_languages):
if rule_matches(rule, audio_languages, subtitle_languages, states):
log.debug("Language tag rule matched: %s -> %s", rule, tag)
return str(tag)
@@ -47,29 +64,43 @@ def rule_matches(
rule: dict[str, Any],
audio_languages: Sequence[Language],
subtitle_languages: Sequence[Language],
states: Optional[Mapping[str, bool]] = None,
) -> bool:
"""Return True when every condition in the rule matches the tracks."""
unknown = [key for key in rule if key not in (*LANGUAGE_CONDITIONS, *STATE_CONDITIONS, "tag")]
if unknown:
log.warning("Language tag rule has unknown key(s) %s, skipping: %s", ", ".join(sorted(unknown)), rule)
return False
has_condition = False
audio_lang = rule.get("audio")
if audio_lang is not None:
has_condition = True
if not is_close_match(audio_lang, list(audio_languages)):
if not any(_matches(lang, audio_languages) for lang in _as_list(audio_lang)):
return False
subs_contain = rule.get("subs_contain")
if subs_contain is not None:
has_condition = True
if not is_close_match(subs_contain, list(subtitle_languages)):
if not any(_matches(lang, subtitle_languages) for lang in _as_list(subs_contain)):
return False
subs_contain_all = rule.get("subs_contain_all")
if subs_contain_all is not None:
has_condition = True
if not isinstance(subs_contain_all, list):
subs_contain_all = [subs_contain_all]
for lang in subs_contain_all:
if not is_close_match(lang, list(subtitle_languages)):
for lang in _as_list(subs_contain_all):
if not _matches(lang, subtitle_languages):
return False
for name in STATE_CONDITIONS:
wanted = rule.get(name)
if wanted is not None:
has_condition = True
if not isinstance(wanted, bool):
log.warning("Language tag rule condition %r must be true or false, skipping: %s", name, rule)
return False
if wanted is not bool((states or {}).get(name)):
return False
if not has_condition:
@@ -77,3 +108,21 @@ def rule_matches(
return False
return True
def _as_list(value: Any) -> list[Any]:
"""Return the rule value as a list, so a scalar and a one-item list behave the same."""
return value if isinstance(value, list) else [value]
def _matches(lang: Any, languages: Sequence[Language]) -> bool:
"""Return True when the rule language closely matches one of the track languages.
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