refactor(dl): move track selection into core/tracks/selection.py

This commit is contained in:
imSp4rky
2026-11-24 13:48:50 -07:00
parent e7c95f03e9
commit b7018c9b27
9 changed files with 1014 additions and 744 deletions
+2 -1
View File
@@ -9,10 +9,11 @@ from typing import Any
import pytest
from unshackle.commands.dl import hybrid_source_tracks, select_hybrid_bases
from unshackle.commands.dl import hybrid_source_tracks
from unshackle.core.tracks import Video
from unshackle.core.tracks import dv_fixup as dv_fixup_mod
from unshackle.core.tracks.dv_fixup import apply_dv_fixup
from unshackle.core.tracks.selection import select_hybrid_bases
pytestmark = pytest.mark.unit
+1 -3
View File
@@ -20,13 +20,10 @@ import unshackle.commands.dl as dl_module
from tests.remote.unit.test_remote_service_helpers import _sent_create_data
from unshackle.commands.dl import (
generated_dv_ranges,
hybrid_gate_failure,
hybrid_plan,
hybrid_source_tracks,
hybrid_step_error,
keep_generated_dv_bases,
missing_hybrid_error,
select_hybrid_bases,
)
from unshackle.core.api import download_manager, handlers
from unshackle.core.api.handlers import validate_download_parameters
@@ -44,6 +41,7 @@ from unshackle.core.tracks.hybrid import (
nits_to_pq,
pq_to_nits,
)
from unshackle.core.tracks.selection import hybrid_gate_failure, keep_generated_dv_bases, select_hybrid_bases
pytestmark = pytest.mark.unit
+14 -23
View File
@@ -1,15 +1,16 @@
"""The kind-only flags: --audio-description-only and --forced-subs-only.
The filters in dl.result are not extractable without executing the whole download loop, so
their wiring is pinned against the source, the same way test_required_langs_gate does it.
Their filters are tested through TrackSelection in test_track_selection.
"""
from __future__ import annotations
import inspect
from types import SimpleNamespace
from typing import Any
import pytest
from tests.lang_selection import test_kind_only_selection as harness
from unshackle.commands.dl import dl
from unshackle.core.api.handlers import validate_download_parameters
from unshackle.core.utilities import kind_only_conflict
@@ -68,23 +69,13 @@ def test_api_rejects_a_non_boolean_flag(key):
assert validate_download_parameters({**BASE, key: None}) is None
class TestFilterWiring:
source = inspect.getsource(dl.result)
def test_ado_runs_when_the_title_has_no_separate_audio(self):
# embedded audio is standard audio: the filter must sit before the `len(...) > 0` guard
ado = self.source.index("if keep_audio and audio_description_only:")
guard = self.source.index("if keep_audio and len(title.tracks.audio) > 0:")
assert ado < guard
def test_ado_does_not_count_embedded_audio(self):
# both the --require-audio gate and the missing-language check
assert self.source.count("keep_videos and not audio_description_only") == 2
def test_only_filters_keep_one_kind(self):
assert "title.tracks.select_audio(lambda x: x.descriptive)" in self.source
assert "title.tracks.select_subtitles(lambda x: x.forced)" in self.source
def test_fso_implies_forced_subs(self):
# services read forced_subs from the ctx params to fetch forced tracks at all
assert "if forced_s_lang or fsl_excl or forced_subs_only:" in self.source
@pytest.mark.parametrize("flags", [{"forced_subs_only": True}, {"forced_s_lang": ["en"]}, {"forced_s_lang": ["-en"]}])
def test_a_forced_flag_turns_forced_subs_on_for_the_service(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, flags: dict[str, Any]
) -> None:
# services read forced_subs from the ctx params to fetch forced tracks at all
service = harness.FakeService({1: {"forced": True}})
params = {"forced_subs": False}
service.ctx = SimpleNamespace(parent=SimpleNamespace(params=params)) # type: ignore[attr-defined]
harness.run(monkeypatch, caplog, {}, service=service, **flags)
assert params["forced_subs"] is True
@@ -1,8 +1,9 @@
"""Run the kind-only filters through the real dl.result() selection loop.
"""Run track selection through the real dl.result() loop, for what the run does with a skip.
A fake service hands in-memory tracks to the loop, and the run stops at the first
title that reaches ``Tracks.tree``, the step right after selection. A title with no
track of the kind never gets there, so what the hook records is what the run kept.
title that reaches ``Tracks.tree``, the step right after selection. What a selection keeps
is tested through TrackSelection in test_track_selection; these tests cover the run:
when a skip stops it, what it reports, and how it settles the post-script groups.
"""
from __future__ import annotations
@@ -136,29 +137,6 @@ def run(
return None
def test_ado_keeps_the_descriptive_track_and_the_other_types(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
ids = run(monkeypatch, caplog, {1: {"ad": True, "forced": True}}, audio_description_only=True)
assert ids == {"video": ["v"], "audio": ["ad"], "subs": ["s"]}
def test_fso_keeps_the_forced_track_and_the_other_types(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
ids = run(monkeypatch, caplog, {1: {"ad": True, "forced": True}}, forced_subs_only=True)
assert ids == {"video": ["v"], "audio": ["a"], "subs": ["sf"]}
def test_only_flags_with_their_type_flags_give_a_single_kind(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
ids = run(monkeypatch, caplog, {1: {"ad": True, "forced": True}}, audio_description_only=True, audio_only=True)
assert ids == {"video": [], "audio": ["ad"], "subs": []}
ids = run(monkeypatch, caplog, {1: {"ad": True, "forced": True}}, forced_subs_only=True, subs_only=True)
assert ids == {"video": [], "audio": [], "subs": ["sf"]}
@pytest.mark.parametrize("flag", ["audio_description_only", "forced_subs_only"])
def test_a_single_title_with_no_such_track_exits(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, flag: str
@@ -218,20 +196,6 @@ def test_skip_missing_skips_the_title_and_reports_it(
assert {"skipped_titles": [{"title": "Show S01E01", "reason": "Required audio language(s) not found: ko"}]} in sink
def test_require_audio_video_and_subs_work_together(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
ids = run(monkeypatch, caplog, {1: {}}, require_audio=["en"], require_video=["en"], require_subs=["en"])
assert ids == {"video": ["v"], "audio": ["a"], "subs": ["s"]}
assert run(monkeypatch, caplog, {1: {}}, require_audio=["ko"], require_video=["ko"], require_subs=["ko"]) == 1
assert (
"Required audio language(s) not found: ko; Required video language(s) not found: ko; "
"Required subtitle language(s) not found: ko"
) in caplog.text
assert run(monkeypatch, caplog, {1: {}}, require_audio=["en"], require_video=["ko"], require_subs=["en"]) == 1
assert "Show S01E01: Required video language(s) not found: ko" in caplog.text
def test_skip_missing_skips_a_filter_miss_and_continues(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
@@ -336,19 +300,42 @@ def test_a_skipped_title_settles_its_post_script_group(
assert seen.count("Show S01E01") == settled
class LcevcService(FakeService):
"""A 540p base video and the 1080p LCEVC enhancement layer that decodes on top of it."""
class CaptionlessService(FakeService):
"""A service that finds out in get_tracks that the title has no subtitles, and turns them off."""
def get_tracks(self, title: Episode) -> Tracks:
tracks = super().get_tracks(title)
tracks.videos[0].height = 540
tracks.add(Video(id_="lcevc", url="https://x/l", language="en", codec=Video.Codec.LCEVC, height=1080))
tracks.subtitles = []
self.NO_SUBTITLES = True
return tracks
def test_an_lcevc_layer_is_left_out_unless_asked_for(
def test_no_subtitles_set_in_get_tracks_turns_the_subtitle_requirement_off(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
assert run(monkeypatch, caplog, {1: {}}, service=LcevcService({1: {}}))["video"] == ["v"]
asked = run(monkeypatch, caplog, {1: {}}, service=LcevcService({1: {}}), vcodec=[Video.Codec.LCEVC])
assert asked["video"] == ["lcevc"]
ids = run(monkeypatch, caplog, {1: {}}, service=CaptionlessService({1: {}}), require_subs=["en"])
assert ids == {"video": ["v"], "audio": ["a"], "subs": []}
class Muxed(BaseException):
"""Stops the run at the first mux."""
def test_a_failed_hybrid_muxes_the_ranges_it_falls_back_to(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
"""The mux step must see the fallback ranges, or it runs the hybrid step on an SDR title."""
def hybrid_step(*args: Any, **kwargs: Any) -> None:
raise AssertionError("the hybrid step ran for a title that fell back to SDR")
def mux(*args: Any, **kwargs: Any) -> None:
raise Muxed()
stub_hybrid(monkeypatch)
monkeypatch.setattr("unshackle.commands.dl.hybrid_plan", hybrid_step)
monkeypatch.setattr(Tracks, "mux", mux)
ranges = [Video.Range.HYBRID, Video.Range.SDR]
with pytest.raises(Muxed):
run(monkeypatch, caplog, {1: {}}, to_end=True, video_only=True, range_=ranges, best_available=True)
assert "continuing with SDR" in caplog.text
@@ -139,19 +139,6 @@ def test_require_subs_no_longer_conflicts_with_s_lang():
)
def test_all_three_require_flags_share_one_gate():
import inspect as _inspect
from unshackle.commands import dl as dl_module
source = _inspect.getsource(dl_module.dl.result)
# the sub gate must not short-circuit the s_lang branch any more
assert "downloading all available subtitles" not in source
for kind in ("audio", "video", "subtitle"):
assert f'"{kind}",' in source
assert "missing_required_langs(required, available, title.language, exact=exact_lang)" in source
def test_exact_lang_turns_off_the_bare_tag_fallback():
assert missing_required_langs(["en"], ["en-GB"]) == []
assert missing_required_langs(["en"], ["en-GB"], exact=True) == ["en"]
@@ -1,18 +1,20 @@
"""The dl.result call site of missing_required_langs, and inputs the unit tests skip.
"""The required-language gate of the track selection, and inputs the unit tests skip.
The gate in dl.result is not extractable without executing the whole download loop, so
its wiring is pinned the same way test_required_langs pins download_manager: against the
source. The value inputs cover what the helper's own tests leave out — real tracks carry
The gate runs in TrackSelection.select, so its tests cross that interface with real tracks.
The value inputs cover what the helper's own tests leave out: real tracks carry
langcodes.Language objects, not strings.
"""
from __future__ import annotations
import inspect
from typing import Any
import pytest
from langcodes import Language
from unshackle.commands.dl import dl
from tests.lang_selection import test_kind_only_selection as harness
from tests.lang_selection.test_track_selection import audio, episode, selection, standard, video
from unshackle.core.tracks.selection import Kept, Skip
from unshackle.core.utilities import missing_required_langs
@@ -37,37 +39,76 @@ def test_requirement_checks_the_catalogue_not_the_selection():
assert missing_required_langs(["fr"], ["en", "ko", "ja", "fr"]) == []
class TestGateWiring:
"""Pin the dl.result gate's shape; a silent rewire is otherwise invisible to tests."""
def test_the_gate_is_disabled_with_the_track_kind() -> None:
# --no-audio / -V must not fail on a requirement the download cannot honour
assert isinstance(selection(require_audio=["ko"], no_audio=True).select(standard(), False), Kept)
assert isinstance(selection(require_video=["ko"], audio_only=True).select(standard(), False), Kept)
source = inspect.getsource(dl.result)
def test_gate_is_disabled_with_the_track_kind(self):
# --no-audio / -V must not fail on a require_audio the download cannot honour
assert "require_audio if keep_audio else []" in self.source
assert "require_video if keep_videos else []" in self.source
def test_the_gate_counts_audio_embedded_in_a_kept_video() -> None:
def title() -> Any:
return episode(video(data={"audio_language": "ko"}), audio())
def test_gate_counts_audio_embedded_in_kept_video(self):
assert "embedded_audio_langs(title.tracks.videos, keep_videos and not audio_description_only)" in self.source
assert isinstance(selection(require_audio=["ko"]).select(title(), False), Kept)
missing = Skip("Required audio language(s) not found: ko")
assert selection(require_audio=["ko"], audio_only=True).select(title(), False) == missing
def test_gate_honours_exact_lang(self):
assert "missing_required_langs(required, available, title.language, exact=exact_lang)" in self.source
def test_gate_reads_tracks_before_the_keep_flags_empty_them(self):
# the availability lists must be built before `if not keep_videos:` clears
# title.tracks.videos, or embedded audio could never satisfy a requirement
gate = self.source.index("missing_required_langs(required")
reset = self.source.index("if not keep_videos:")
assert gate < reset
def test_ado_does_not_count_audio_embedded_in_the_video_at_the_gate() -> None:
title = episode(video(data={"audio_language": "ko"}), audio("ad", bitrate=1, descriptive=True))
sel = selection(require_audio=["ko"], audio_description=True, audio_description_only=True)
assert sel.select(title, False) == Skip("Required audio language(s) not found: ko")
def test_require_and_exclude_clash_is_rejected_per_flag(self):
# --require-audio en with -l all,-en can never be satisfied as the user
# meant it, so it must die at parse time, against each flag's own
# exclusion list (-vl/-al cascade from -l only when unset)
assert "cannot be required and excluded at the same time" in self.source
for pair in (
'("--require-audio", require_audio, audio_excl)',
'("--require-video", require_video, video_excl)',
'("--require-subs", require_subs, s_lang_excl)',
):
assert pair in self.source
def test_a_run_with_every_required_language_present_keeps_the_title() -> None:
sel = selection(require_audio=["en"], require_video=["en"], require_subs=["en"])
assert isinstance(sel.select(standard(), False), Kept)
def test_the_gate_honours_exact_lang() -> None:
def title() -> Any:
return episode(video(), audio(language="en-GB"))
assert isinstance(selection(require_audio=["en"]).select(title(), False), Kept)
missing = Skip("Required audio language(s) not found: en")
assert selection(require_audio=["en"], exact_lang=True).select(title(), False) == missing
def test_the_gate_reads_the_tracks_before_any_filter() -> None:
title = episode(video(), audio("en", "en", bitrate=1), audio("ko", "ko", bitrate=1))
outcome = selection(a_lang=["en"], require_audio=["ko"]).select(title, False)
assert isinstance(outcome, Kept)
assert [a.id for a in outcome.tracks.audio] == ["en"]
def test_every_kind_misses_in_one_reason() -> None:
sel = selection(require_audio=["ko"], require_video=["ko"], require_subs=["ko"])
assert sel.select(standard(), False) == Skip(
"Required audio language(s) not found: ko; Required video language(s) not found: ko; "
"Required subtitle language(s) not found: ko"
)
@pytest.mark.parametrize(
("flags", "clash"),
[
({"require_audio": ["en"], "lang": ["all", "-en"]}, "--require-audio: en"),
({"require_video": ["en"], "v_lang": ["all", "-en"]}, "--require-video: en"),
({"require_subs": ["en"], "s_lang": ["all", "-en"]}, "--require-subs: en"),
({"require_audio": ["-en"]}, "--require-audio: en"),
],
)
def test_a_required_and_excluded_language_stops_the_run(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, flags: dict[str, Any], clash: str
) -> None:
assert harness.run(monkeypatch, caplog, {1: {}}, **flags) == 1
assert f"{clash} cannot be required and excluded at the same time." in caplog.text
def test_a_language_override_does_not_inherit_the_lang_exclusions(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
# -al and -vl name languages, so they replace -l and its -en
flags: dict[str, Any] = {"require_audio": ["en"], "a_lang": ["en"], "v_lang": ["all"], "lang": ["all", "-en"]}
ids = harness.run(monkeypatch, caplog, {1: {}}, **flags)
assert ids["audio"] == ["a"]
@@ -0,0 +1,159 @@
"""Track selection through its interface: real tracks in, the kept tracks or the skip reason out."""
from __future__ import annotations
import logging
from dataclasses import fields
from typing import Any
import pytest
from unshackle.core.titles import Episode
from unshackle.core.tracks import Audio, Subtitle, Tracks, Video
from unshackle.core.tracks.selection import Kept, Skip, TrackSelection
def selection(**flags: Any) -> TrackSelection:
"""A TrackSelection with every filter off but the given flags."""
off: dict[str, Any] = {}
for flag in fields(TrackSelection):
off[flag.name] = [] if str(flag.type).startswith("list") else None if "Optional" in str(flag.type) else False
return TrackSelection(**{**off, **flags})
class EXAMPLE:
"""The service class an Episode names."""
def video(id_: str = "v", language: str = "en", **kwargs: Any) -> Video:
kwargs.setdefault("codec", Video.Codec.AVC)
kwargs.setdefault("range_", Video.Range.SDR)
return Video(id_=id_, url=f"https://cdn.example/{id_}", language=language, **kwargs)
def audio(id_: str = "a", language: str = "en", **kwargs: Any) -> Audio:
return Audio(id_=id_, url=f"https://cdn.example/{id_}", language=language, codec=Audio.Codec.AAC, **kwargs)
def subtitle(id_: str = "s", language: str = "en", **kwargs: Any) -> Subtitle:
return Subtitle(id_=id_, url=f"https://cdn.example/{id_}", language=language, codec=Subtitle.Codec.WebVTT, **kwargs)
def episode(*tracks: Any, language: str = "en") -> Episode:
title = Episode(id_="show-s01-e001", service=EXAMPLE, title="Show", season=1, number=1, language=language)
title.tracks = Tracks(list(tracks))
return title
def standard(**extra: bool) -> Episode:
"""One video, one audio and one subtitle in English; ad adds a descriptive track, forced a forced subtitle."""
tracks: list[Any] = [video(), audio(bitrate=128_000)]
if extra.get("ad"):
tracks.append(audio("ad", bitrate=1, descriptive=True))
tracks.append(subtitle())
if extra.get("forced"):
tracks.append(subtitle("sf", forced=True))
return episode(*tracks)
def kept(outcome: Kept | Skip) -> dict[str, list[str]]:
assert isinstance(outcome, Kept), outcome
return {
"video": [t.id for t in outcome.tracks.videos],
"audio": [t.id for t in outcome.tracks.audio],
"subs": [t.id for t in outcome.tracks.subtitles],
}
def test_the_defaults_keep_every_track() -> None:
assert kept(selection().select(standard(), False)) == {"video": ["v"], "audio": ["a"], "subs": ["s"]}
def test_ado_keeps_the_descriptive_track_and_the_other_types() -> None:
sel = selection(audio_description=True, audio_description_only=True)
assert kept(sel.select(standard(ad=True, forced=True), False)) == {"video": ["v"], "audio": ["ad"], "subs": ["s"]}
def test_fso_keeps_the_forced_track_and_the_other_types() -> None:
sel = selection(forced_subs=True, forced_subs_only=True)
assert kept(sel.select(standard(ad=True, forced=True), False)) == {"video": ["v"], "audio": ["a"], "subs": ["sf"]}
def test_only_flags_with_their_type_flags_give_a_single_kind() -> None:
sel = selection(audio_description=True, audio_description_only=True, audio_only=True)
assert kept(sel.select(standard(ad=True, forced=True), False)) == {"video": [], "audio": ["ad"], "subs": []}
sel = selection(forced_subs=True, forced_subs_only=True, subs_only=True)
assert kept(sel.select(standard(ad=True, forced=True), False)) == {"video": [], "audio": [], "subs": ["sf"]}
@pytest.mark.parametrize(
("flags", "reason"),
[
({"audio_description": True, "audio_description_only": True}, "There's no audio description track."),
(
{"forced_subs": True, "forced_subs_only": True},
"There's no forced subtitle track for the selected languages.",
),
({"subs_only": True, "s_lang": ["fr"]}, "There's no track left for the selected options."),
],
)
def test_a_kind_only_miss_is_a_kind_only_skip(flags: dict[str, Any], reason: str) -> None:
assert selection(**flags).select(standard(), False) == Skip(reason, kind_only=True)
def test_ado_runs_when_the_title_has_no_separate_audio() -> None:
title = episode(video(data={"audio_language": "en"}))
sel = selection(audio_description=True, audio_description_only=True)
assert sel.select(title, False) == Skip("There's no audio description track.", kind_only=True)
def test_ado_does_not_count_audio_embedded_in_the_video() -> None:
def title() -> Episode:
return episode(video(data={"audio_language": "ko"}), audio("ad", bitrate=1, descriptive=True))
assert kept(selection(audio_description=True, a_lang=["ko"]).select(title(), False))["video"] == ["v"]
sel = selection(audio_description=True, audio_description_only=True, a_lang=["ko"])
assert sel.select(title(), False) == Skip("ko not found in audio description tracks")
def test_a_missing_audio_language_skips_unless_best_available(caplog: pytest.LogCaptureFixture) -> None:
def title() -> Episode:
return episode(video(), audio("ja", "ja", bitrate=1), audio("en", "en", bitrate=1), language="ja")
assert selection(a_lang=["orig", "ko", "en"]).select(title(), False) == Skip("ko not found in audio tracks")
with caplog.at_level(logging.WARNING):
outcome = selection(a_lang=["orig", "ko", "en"], best_available=True).select(title(), False)
assert kept(outcome)["audio"] == ["ja", "en"]
assert "ko not found in audio tracks, continuing with: orig, en" in caplog.text
def test_an_lcevc_layer_is_left_out_unless_asked_for() -> None:
def title() -> Episode:
return episode(video(height=540), video("lcevc", codec=Video.Codec.LCEVC, height=1080), audio())
assert kept(selection().select(title(), False))["video"] == ["v"]
assert kept(selection(vcodec=[Video.Codec.LCEVC]).select(title(), False))["video"] == ["lcevc"]
def test_a_failed_hybrid_falls_back_to_the_other_ranges_only_with_best_available() -> None:
ranges = [Video.Range.HYBRID, Video.Range.SDR]
failure = "HYBRID needs HDR10/HDR10+ and DV tracks, available ranges: SDR"
assert selection(range_=ranges).select(standard(), False) == Skip(failure)
outcome = selection(range_=ranges, best_available=True).select(standard(), False)
assert isinstance(outcome, Kept)
assert outcome.ranges == [Video.Range.SDR]
assert kept(outcome)["video"] == ["v"]
def test_the_selection_can_run_on_every_title_of_a_run() -> None:
sel = selection(no_subs=True, range_=[Video.Range.HYBRID, Video.Range.SDR], best_available=True)
for _ in range(2):
outcome = sel.select(standard(), False)
assert isinstance(outcome, Kept)
assert outcome.ranges == [Video.Range.SDR]
assert kept(outcome)["subs"] == []
assert sel.range_ == [Video.Range.HYBRID, Video.Range.SDR]
def test_a_service_without_subtitles_drops_them_and_their_requirement() -> None:
assert kept(selection(require_subs=["ko"]).select(standard(), True)) == {"video": ["v"], "audio": ["a"], "subs": []}