Compare commits

...
3 Commits
Author SHA1 Message Date
imSp4rky a5f5e7d14d refactor(tracks): honour the best token and share one match rule
sort_subtitles resolved only the all token, while the video and audio sorts
resolved all and best. by_language now asks matching_languages rather than
repeating the RFC 4647 preference, with no behaviour change.
2026-08-03 10:29:09 -06:00
imSp4rky a6997f6bca 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.
2026-08-03 10:15:05 -06:00
imSp4rky 4e1ccf3230 feat(dl): add -fsl/--forced-s-lang to filter forced subtitles by language 2026-08-03 09:27:40 -06:00
15 changed files with 401 additions and 57 deletions
+1
View File
@@ -366,6 +366,7 @@ Create a download job. Requires `service` and `title_id`; every other field is a
| `lang` / `v_lang` / `a_lang` / `s_lang` | string[] | `["orig"]` / `[]` / `[]` / `["all"]` | Language filters. |
| `require_subs` | string[] | `[]` | Required subtitle languages. |
| `forced_subs` | boolean | `false` | Include forced subtitles. |
| `forced_s_lang` | string[] | `[]` | Forced subtitle language(s); implies `forced_subs`. |
| `exact_lang` | boolean | `false` | Exact language matching. |
| `sub_format` | string | `null` | Output subtitle format. |
| `video_only` / `audio_only` / `subs_only` / `chapters_only` | boolean | `false` | Track-type restriction (at most one). |
+8 -1
View File
@@ -96,9 +96,16 @@ unshackle dl [OPTIONS] SERVICE [SERVICE ARGS...]
| `-sl`, `--s-lang` | `all` | Subtitle language(s). |
| `--require-subs` | - | Required subtitle langs; keeps **all** subs only if these exist. **Cannot combine with `--s-lang`.** |
| `-fs`, `--forced-subs` | off | Include forced subtitle tracks. |
| `--exact-lang` | off | Exact matching only: `-l es-419` matches `es-419`, not `es-ES`. |
| `-fsl`, `--forced-s-lang` | none | Language(s) wanted for forced subtitles; implies `-fs`. |
| `--exact-lang` | off | Exact matching only: `-l es-419` matches `es-419`, not `es-ES`. Applies to selection and to sort order. |
| `--sub-format` | - | Output subtitle format (`SRT`/`srt`, `VTT`/`webvtt`, `ASS`/`ssa`, `TTML`, `SMI`, ...), or `original` to keep the source format. |
!!! tip "These flags select languages, they do not order them"
Naming languages with `-l` or `-sl` removes the others. To keep every language but put
your preferred ones first, use `audio.language_priority` and
[`subtitle.language_priority`](../reference/configuration.md#subtitle) in your
configuration file.
The special language tokens `orig`, `all`, and `best` are honoured everywhere a language is expected.
### Title & episode selection
+24
View File
@@ -254,6 +254,26 @@ it is used. You can override each stream type independently:
unshackle dl -al en EXAMPLE 81234567
```
### Sort order
`-l` and `-sl` **select** languages: naming some removes the rest. To keep every language
but decide which ones come first, set a priority list in your configuration file:
```yaml title="unshackle.yaml"
audio:
language_priority: [orig, en]
subtitle:
group_by: language
language_priority: [en, es, fr]
```
Subtitles then start with English, Spanish, and French. The languages you leave out follow
alphabetically, after the title's original language. Nothing is removed. Audio works the
same way, but the languages you leave out keep their bitrate and codec order instead of an
alphabetical one.
See [`subtitle.language_priority`](../reference/configuration.md#subtitle) for the details.
### Exact vs fuzzy matching
By default language matching is fuzzy: `-l en` also accepts `en-US`, `en-GB`, etc. (up
@@ -289,6 +309,9 @@ download on the presence of a specific subtitle track.
- `-fs` / `--forced-subs`: include forced subtitle tracks (signs/foreign dialogue).
Without this flag, forced subs are dropped from selection.
- `-fsl` / `--forced-s-lang`: keep forced subtitles only in these languages (implies
`-fs`). Works independently of `--s-lang`, so `-sl all -fsl en` grabs every full
subtitle but only the English forced track.
- `--sub-format`: set the output subtitle format, converting only when necessary.
Accepts codec names/values and common aliases (`srt`, `vtt`, `ass`, `ssa`, `ttml`,
etc.), or the literal `original` to keep the source format.
@@ -578,6 +601,7 @@ authoritative list.
| `--v-lang` | `-vl` | Video-only language override. |
| `--s-lang` | `-sl` | Subtitle language(s); default `all`. |
| `--forced-subs` | `-fs` | Include forced subtitles. |
| `--forced-s-lang` | `-fsl` | Forced subtitle language(s); implies `-fs`. |
| `--sub-format` | | Output subtitle format. |
| `--wanted` | `-w` | Episode/season range. |
| `--select-titles` | | Interactively pick episodes or films. |
+15
View File
@@ -70,6 +70,7 @@ Subtitle selection happens through `dl` flags. The most important is language se
| `-sl`, `--s-lang` | Language(s) wanted for subtitles. Defaults to `all`. |
| `--require-subs` | Require these languages to exist; if present, download **all** subtitles. Cannot be combined with `--s-lang`. |
| `-fs`, `--forced-subs` | Include forced subtitle tracks (excluded by default). |
| `-fsl`, `--forced-s-lang` | Language(s) wanted for forced subtitles; implies `-fs`. |
| `--exact-lang` | Exact language matching, with no regional variants. |
| `-S`, `--subs-only` | Download only subtitle tracks. |
| `-ns`, `--no-subs` | Do not download subtitle tracks at all. |
@@ -121,6 +122,18 @@ default**. Add `-fs` / `--forced-subs` to include them:
unshackle dl --s-lang en --forced-subs EXAMPLE 81234567
```
`-fs` keeps forced tracks in every selected language. If you only want forced tracks
in certain languages, use `-fsl` / `--forced-s-lang` instead. It implies `-fs`, so
you do not need both:
```shell title="All full subtitles, but only the English forced track"
unshackle dl --s-lang all --forced-s-lang en EXAMPLE 81234567
```
If you pass both flags, `-fsl` wins and keeps only forced tracks in its languages.
It also understands `orig` (the title's original language) and `all` (every forced
track, same as plain `-fs`).
## Track types: forced, SDH, and CC
Every subtitle track carries flags describing what kind of captions it holds. These
@@ -363,6 +376,8 @@ subtitle:
| `convert_before_strip` | `true` | `true` / `false` | Convert a subtitle to SRT before stripping SDH (for non-SubtitleEdit engines). |
| `output_mode` | `mux` | `mux`, `sidecar`, `both` | Whether subtitles are embedded, written as sidecars, or both. |
| `sidecar_format` | `srt` | a format name (e.g. `srt`, `vtt`) or `original` | Format used for sidecar files. |
| `group_by` | `type` | `type`, `language` | Whether all tracks of one type stay together, or each language stays next to its own variants. |
| `language_priority` | *(unset)* | a list of languages | Languages to sort to the top. The rest keep the default order. Nothing is removed. |
!!! tip "SubtitleEdit is optional but recommended"
Several high-fidelity paths (the best-quality conversions and the SubtitleEdit SDH
+34 -1
View File
@@ -320,6 +320,7 @@ Common keys (a useful subset; every `dl` flag works):
| `channels` | float | *(unset)* | Audio channels, e.g. `6` for 5.1. |
| `sub_format` | str | *(unset)* | Convert subtitles to this format (`srt`, `vtt`, `original`, ...). |
| `forced_subs` | bool | `false` | Include forced subtitle tracks. |
| `forced_s_lang` | list | `[]` | Forced subtitle language(s); implies `forced_subs`. |
| `no_subs` / `no_audio` / `no_chapters` | bool | `false` | Skip that track type. |
| `downloads` | int | `1` | Tracks downloaded concurrently. |
| `workers` | int | *(downloader default)* | Threads per track. |
@@ -377,6 +378,7 @@ written as sidecar files. See [Subtitles](../guide/subtitles.md) for the full gu
| `sidecar_format` | str | `"srt"` | Format for sidecar files when `output_mode: sidecar`. |
| `type_priority` | list | *(unset)* | Ordered ranking of subtitle types (`forced`, `normal`, `sdh`; CC counts as SDH). Types you leave out fall to the end. |
| `group_by` | str | `"type"` | Which key groups the subtitle tracks. `type` puts all forced tracks together, then all normal, then all SDH. `language` keeps each language next to its own variants. |
| `language_priority` | list | *(unset)* | Languages to sort to the top, in the order you give. The rest keep the default order: original language first, then alphabetical. Nothing is removed. |
```yaml
subtitle:
@@ -404,6 +406,33 @@ subtitle:
`type_priority` still sets the order of the variants, so with `group_by: language` it
controls the order inside each language.
!!! note "`language_priority` sorts languages, it does not select them"
By default the title's original language comes first and every other language follows
alphabetically. For an English title that gives English, Arabic, Bulgarian, and the
rest. Give `language_priority` the languages you want first:
```yaml
subtitle:
group_by: language
language_priority: [en, es, fr]
```
| | Result for an English title |
|---|---|
| Default | English, Arabic, Bulgarian, Spanish, French, Japanese |
| With the list above | English, Spanish, French, Arabic, Bulgarian, Japanese |
This is only an order. Every other language is still downloaded, which is what makes
it different from `-sl`: `-sl en,es,fr` **removes** all other subtitles.
Use `orig` in the list for the title's original language. A base tag also covers its
regional forms, so `en` sorts `en-US` and `en-GB`, but `zh` does **not** cover
`zh-Hant`, which you must name. The sort ignores entries that match no track, and it
ignores entries that are not valid language tags.
`--exact-lang` applies here too: with it, `en` sorts only `en`, and `en-US` falls to
the alphabetical tail with the rest. Name each tag you want when you use that flag.
!!! note "`type_priority` also picks the default subtitle"
At mux time the first track in the default subtitle language gets the `default` flag.
The built-in order is `forced`, `normal`, `sdh`, which means a forced track becomes
@@ -420,13 +449,17 @@ subtitle:
- **Type:** `dict`  ·  **Default:** `{}`
Audio handling options. The most notable sub-key is **`codec_priority`**, an ordered list of
audio codecs used to break ties in track selection.
audio codecs used to break ties in track selection. **`language_priority`** is an ordered list
of languages that sort to the top of the audio tracks.
```yaml
audio:
codec_priority:
- EAC3
- AC3
language_priority:
- orig
- en
```
!!! note "`codec_priority` is a soft priority: nothing is dropped"
@@ -0,0 +1,25 @@
from __future__ import annotations
import pytest
from unshackle.core.utilities import keep_forced_subtitle
@pytest.mark.parametrize(
"forced,language,forced_s_lang,exact,expected",
[
(False, "en", [], False, True),
(False, "de", ["en"], False, True),
(True, "en", [], False, False),
(True, "en", ["en"], False, True),
(True, "en-US", ["en"], False, True),
(True, "de", ["en"], False, False),
(True, "de", ["en", "de"], False, True),
# CLDR rates paradigm-regional pairs (en/en-US) distance 0, so exact still matches
(True, "en-US", ["en"], True, True),
(True, "en", ["en"], True, True),
(True, "es-419", ["es-ES"], True, False),
],
)
def test_keep_forced_subtitle(forced: bool, language: str, forced_s_lang: list[str], exact: bool, expected: bool):
assert keep_forced_subtitle(forced, language, forced_s_lang, exact) is expected
@@ -0,0 +1,33 @@
from __future__ import annotations
from typing import Sequence
import pytest
from unshackle.core.utilities import matching_languages
POOL = ["ar", "en", "en-GB", "en-US", "ja"]
@pytest.mark.parametrize(
("language", "available", "exact", "expected"),
[
("en", POOL, False, {"en", "en-GB", "en-US"}),
# CLDR rates en/en-US at distance 0, so exact mode leans on the RFC 4647 string preference
("en", POOL, True, {"en"}),
("en-GB", POOL, True, {"en-GB"}),
# no string-equal tag, so exact mode falls back to the distance match
("zh", ["ar", "cmn", "ja"], True, {"cmn"}),
("en", ["ar", "ja"], False, set()),
("en", [], False, set()),
("en", ["ar", None, "en"], True, {"en"}),
# unparseable tags (config typos) must match nothing, never raise
("engrish", POOL, False, set()),
("engrish", POOL, True, set()),
("", POOL, False, set()),
("", POOL, True, set()),
("f", POOL, False, set()),
],
)
def test_matching_languages(language: str, available: Sequence[str], exact: bool, expected: set[str]) -> None:
assert matching_languages(language, available, exact) == expected
@@ -0,0 +1,24 @@
from __future__ import annotations
from typing import Optional, Sequence
import pytest
from langcodes import Language
from unshackle.core.utilities import resolve_sort_langs
@pytest.mark.parametrize(
("tokens", "original", "expected"),
[
(["orig", "en", "es"], "ja", ["ja", "en", "es"]),
(["orig", "en", "es"], None, ["en", "es"]),
(["orig"], Language.get("pt-BR"), ["pt-BR"]),
(["en", "orig"], "en", ["en"]),
(["en", "es", "en", "fr"], None, ["en", "es", "fr"]),
(["all", "best", "en"], "ja", ["all", "best", "en"]),
([], "ja", []),
],
)
def test_resolve_sort_langs(tokens: Sequence[str], original: Optional[str], expected: list[str]) -> None:
assert resolve_sort_langs(tokens, original) == expected
+90 -2
View File
@@ -3,8 +3,8 @@ import pytest
from unshackle.core.tracks import Subtitle, Tracks
def sub(lang: str, forced: bool = False, sdh: bool = False, cc: bool = False) -> Subtitle:
return Subtitle(
def sub(lang: str, forced: bool = False, sdh: bool = False, cc: bool = False, orig: bool = False) -> Subtitle:
track = Subtitle(
url=f"https://example.test/{lang}-{forced}-{sdh}-{cc}",
language=lang,
codec=Subtitle.Codec.SubRip,
@@ -12,6 +12,8 @@ def sub(lang: str, forced: bool = False, sdh: bool = False, cc: bool = False) ->
sdh=sdh,
cc=cc,
)
track.is_original_lang = orig
return track
def shape(tracks: Tracks) -> list[tuple[str, str]]:
@@ -135,3 +137,89 @@ def test_language_grouping_keeps_regional_variants_adjacent_through_sections() -
("fi", "normal"),
("fi", "sdh"),
]
def langs(tracks: Tracks) -> list[str]:
return [str(s.language) for s in tracks.subtitles]
@pytest.fixture
def many() -> Tracks:
t = Tracks()
t.add([sub(lang, orig=lang == "ja") for lang in ("ar", "bg", "en", "es", "fr", "ja")])
return t
def test_priority_orders_listed_then_rest_alphabetically(many: Tracks) -> None:
many.sort_subtitles(by_language=["en", "es", "fr"], group_by="language")
assert langs(many) == ["en", "es", "fr", "ar", "bg", "ja"]
def test_priority_outranks_the_original_language(many: Tracks) -> None:
# "all" resolves to the original language (ja), which must stay below the named ones
many.sort_subtitles(by_language=["en", "es", "all"], group_by="language")
assert langs(many) == ["en", "es", "ja", "ar", "bg", "fr"]
def test_priority_matches_regional_variants() -> None:
t = Tracks()
t.add([sub("ar"), sub("en-US"), sub("es-419"), sub("ja")])
t.sort_subtitles(by_language=["en", "es"], group_by="language")
assert langs(t) == ["en-US", "es-419", "ar", "ja"]
def test_priority_overlapping_entries_are_harmless() -> None:
t = Tracks()
t.add([sub("ar"), sub("en-GB"), sub("en-US"), sub("es"), sub("ja")])
t.sort_subtitles(by_language=["en", "en-US", "es"], group_by="language")
assert langs(t) == ["en-GB", "en-US", "es", "ar", "ja"]
def test_no_priority_leaves_order_unchanged(many: Tracks) -> None:
many.sort_subtitles(by_language=[], group_by="language")
assert langs(many) == ["ar", "bg", "en", "es", "fr", "ja"]
@pytest.mark.parametrize("token", ["all", "best"])
def test_magic_token_alone_floats_the_original_language(many: Tracks, token: str) -> None:
many.sort_subtitles(by_language=[token], group_by="language")
assert langs(many) == ["ja", "ar", "bg", "en", "es", "fr"]
@pytest.mark.parametrize("token", ["all", "best"])
def test_priority_outranks_either_magic_token(many: Tracks, token: str) -> None:
many.sort_subtitles(by_language=["en", "es", token], group_by="language")
assert langs(many) == ["en", "es", "ja", "ar", "bg", "fr"]
@pytest.fixture
def regionals() -> Tracks:
t = Tracks()
t.add([sub("ar"), sub("en"), sub("en-GB"), sub("en-US"), sub("ja")])
return t
def test_fuzzy_priority_floats_regional_variants(regionals: Tracks) -> None:
regionals.sort_subtitles(by_language=["en"], group_by="language")
assert langs(regionals) == ["en", "en-GB", "en-US", "ar", "ja"]
def test_exact_priority_floats_only_the_named_tag(regionals: Tracks) -> None:
# CLDR rates en/en-US at distance 0, so exact mode needs the RFC 4647 string preference
# to hold en-US back; without it en-US floats and en-GB does not.
regionals.sort_subtitles(by_language=["en"], group_by="language", exact_match=True)
assert langs(regionals) == ["en", "ar", "en-GB", "en-US", "ja"]
def test_exact_priority_still_falls_back_when_no_tag_is_string_equal() -> None:
t = Tracks()
t.add([sub("ar"), sub("cmn"), sub("ja")])
t.sort_subtitles(by_language=["zh"], group_by="language", exact_match=True)
assert langs(t) == ["cmn", "ar", "ja"]
@pytest.mark.parametrize("exact", [False, True])
def test_unparseable_priority_entry_is_ignored(many: Tracks, exact: bool) -> None:
# a config typo in language_priority must not crash the sort
many.sort_subtitles(by_language=["en", "engrish", "f", ""], group_by="language", exact_match=exact)
assert langs(many) == ["en", "ar", "bg", "es", "fr", "ja"]
+61 -33
View File
@@ -80,7 +80,10 @@ from unshackle.core.utilities import (
get_system_fonts,
init_debug_logger,
is_close_match,
is_exact_match,
keep_forced_subtitle,
log_event,
resolve_sort_langs,
suggest_font_packages,
time_elapsed_since,
)
@@ -551,6 +554,13 @@ class dl:
help="Required subtitle languages. Downloads all subtitles only if these languages exist. Cannot be used with --s-lang.",
)
@click.option("-fs", "--forced-subs", is_flag=True, default=False, help="Include forced subtitle tracks.")
@click.option(
"-fsl",
"--forced-s-lang",
type=LANGUAGE_RANGE,
default=[],
help="Languages wanted for forced subtitles, implies -fs. Keeps forced subs only in these languages.",
)
@click.option(
"--exact-lang",
is_flag=True,
@@ -1270,6 +1280,7 @@ class dl:
s_lang: list[str],
require_subs: list[str],
forced_subs: bool,
forced_s_lang: list[str],
exact_lang: bool,
sub_format: Optional[Union[Subtitle.Codec, str]],
video_only: bool,
@@ -1312,6 +1323,15 @@ class dl:
self._remote_service = service if self.server_cdm else None
start_time = time.time()
if forced_s_lang:
# services read forced_subs from raw ctx params, so the implication must be pushed there too
forced_subs = True
if "all" in forced_s_lang:
forced_s_lang = []
ctx = getattr(service, "ctx", None)
if ctx and ctx.parent:
ctx.parent.params["forced_subs"] = True
if skip_dl:
DOWNLOAD_LICENCE_ONLY.set()
@@ -1840,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:
@@ -2370,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_:
@@ -2782,6 +2790,9 @@ class dl:
sys.exit(1)
# filter subtitle tracks
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))
if keep_subtitles and require_subs:
missing_langs = [
lang
@@ -2797,8 +2808,6 @@ class dl:
f"Required languages found ({', '.join(require_subs)}), downloading all available subtitles"
)
elif keep_subtitles and s_lang and "all" not in s_lang:
from unshackle.core.utilities import is_exact_match
match_func = is_exact_match if exact_lang else is_close_match
missing_langs = find_missing_langs(
@@ -2819,19 +2828,38 @@ class dl:
self.log.warning(
f"{missing_str} not found in subtitle tracks, continuing without subtitles"
)
title.tracks.subtitles = []
title.tracks.select_subtitles(
lambda x: (
x.forced and keep_forced_subtitle(x.forced, x.language, fsl, exact_lang)
)
)
else:
self.log.error(missing_str + " not found in tracks")
sys.exit(1)
if s_lang and title.tracks.subtitles:
title.tracks.select_subtitles(lambda x: match_func(x.language, s_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))
)
)
if not title.tracks.subtitles and not best_available:
self.log.error(f"There's no {s_lang} Subtitle Track...")
sys.exit(1)
if keep_subtitles and not forced_subs:
title.tracks.select_subtitles(lambda x: not x.forced)
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)
)
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)})"
)
elif not forced_subs:
title.tracks.select_subtitles(lambda x: not x.forced)
# filter audio tracks
# might have no audio tracks if part of the video, e.g. transport stream hls
+1
View File
@@ -536,6 +536,7 @@ def _perform_download(
s_lang=params.get("s_lang", ["all"]),
require_subs=params.get("require_subs", []),
forced_subs=params.get("forced_subs", False),
forced_s_lang=params.get("forced_s_lang", []),
exact_lang=params.get("exact_lang", False),
sub_format=params.get("sub_format"),
video_only=params.get("video_only", False),
+1
View File
@@ -44,6 +44,7 @@ DEFAULT_DOWNLOAD_PARAMS = {
"s_lang": ["all"],
"require_subs": [],
"forced_subs": False,
"forced_s_lang": [],
"exact_lang": False,
"sub_format": None,
"video_only": False,
+5
View File
@@ -689,6 +689,11 @@ async def download(request: web.Request) -> web.Response:
forced_subs:
type: boolean
description: Include forced subtitle tracks (default - false)
forced_s_lang:
type: array
items:
type: string
description: Languages wanted for forced subtitles, implies forced_subs (default - [])
exact_lang:
type: boolean
description: Use exact language matching (no variants) (default - false)
+20 -20
View File
@@ -7,7 +7,7 @@ from functools import partial
from pathlib import Path
from typing import Any, Callable, Iterator, Optional, Sequence, Union
from langcodes import Language, closest_supported_match
from langcodes import Language
from rich.progress import Progress, SpinnerColumn, TaskID, TextColumn, TimeRemainingColumn
from rich.table import Table
from rich.tree import Tree
@@ -15,7 +15,7 @@ from rich.tree import Tree
from unshackle.core import binaries
from unshackle.core.config import config
from unshackle.core.console import GradientPulseBarColumn, console
from unshackle.core.constants import LANGUAGE_EXACT_DISTANCE, LANGUAGE_MAX_DISTANCE, AnyTrack, TrackT
from unshackle.core.constants import AnyTrack, TrackT
from unshackle.core.events import events
from unshackle.core.tracks.attachment import Attachment
from unshackle.core.tracks.audio import Audio
@@ -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
@@ -342,11 +351,12 @@ class Tracks:
by_type()
# sections
for language in reversed(by_language or []):
if str(language) == "all":
if str(language) in ("all", "best"):
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))
@@ -459,21 +469,11 @@ class Tracks:
def by_language(
tracks: list[TrackT], languages: list[str], per_language: int = 0, exact_match: bool = False
) -> list[TrackT]:
distance = LANGUAGE_EXACT_DISTANCE if exact_match else LANGUAGE_MAX_DISTANCE
selected: list[TrackT] = []
seen_ids: set[str] = set()
for language in languages:
matches = [x for x in tracks if closest_supported_match(str(x.language), [language], distance)]
if exact_match and len(matches) > 1:
# CLDR tag_distance measures intelligibility, not tag identity: it rates a base
# language and its "paradigm" regional variant as the same language (distance 0
# for ar/ar-EG, en/en-US, pt/pt-BR), so exact mode alone cannot separate them.
# Follow RFC 4647 Lookup: prefer the most specific (string-equal) tag, and fall
# back to the fuzzy match only when none exists (e.g. zh matches cmn).
want = Language.get(language).to_tag().casefold()
exact_hits = [x for x in matches if Language.get(str(x.language)).to_tag().casefold() == want]
if exact_hits:
matches = exact_hits
wanted = matching_languages(language, [x.language for x in tracks], exact_match)
matches = [x for x in tracks if str(x.language) in wanted]
# Overlapping tags can still resolve to the same physical track; dedupe by id so
# callers never get duplicate tracks.
for track in matches[: per_language or None]:
+59
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
@@ -163,6 +164,21 @@ def is_exact_match(language: Union[str, Language], languages: Sequence[Union[str
return closest_match(language, list(map(str, languages)))[1] <= LANGUAGE_EXACT_DISTANCE
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 if 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 find_missing_langs(
requested: Sequence[str],
available: Sequence[Union[str, Language, None]],
@@ -180,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.