Compare commits

..
18 Commits
Author SHA1 Message Date
imSp4rky 2f35a4d468 feat(api): aggregate REST download progress with weighting, track labels and mux stage
Replace the class-level Track.download monkeypatch with a per-job progress sink threaded through dl.result(). The API now reports a single aggregate signal instead of each track's bouncing 0-100%:

- bitrate-weighted completion so video/audio dominate subtitles
- completed_tracks/total_tracks counts and active_tracks labels (e.g. "video 2160p DV", "audio en-US 5.1")
- downloads fill 0-90%; repackaging (when needed) and a "muxing" stage carry it to 100% so post-download work is no longer frozen at 100%
- monotonic throughout (handles the download->decrypt callable reuse)

Also:
- accept "HDR10P" as the canonical API range value ("HDR10+" still works)
- declare AUTH_METHODS opt-in on the Service base
- raise typed APIError (WORKER_ERROR/DOWNLOAD_ERROR) from the worker path
- move the progress helpers to unshackle/core/api/progress.py
2026-06-08 15:37:40 -06:00
AviDevandAvi Cohen 1a3cd09fc8 fix(api): repair REST API downloads, add /services flags & live progress (#113)
* feat(api): live download phase, granular progress, swallowed-failure detection, per-request CDM

- Tee Track.download progress so the job reports real percentage (not just 5/100%) and a
  human-readable phase ('downloading video 1080p') via the new job.phase field.
- Detect a swallowed download-worker failure (dl.result() prints 'Download Failed' but
  exits 0) and raise, so the job is marked failed instead of completed-with-no-output.
- Per-request CDM override (dl_instance.cdm_override; get_cdm prefers it) so a job can use
  a specific CDM device without mutating shared config.

* feat(api): expose service capability flags + auth methods in /services

needs_auth / has_search / has_drm derived from which Service hooks are overridden, and
auth_methods inferred from what the service's authenticate() body references (cookies /
credentials), so clients can show only the relevant auth options per service.

* feat(api): per-request credential injection for downloads

Accept a 'credential' ('user:pass') job parameter and feed it into the credentials map that
dl.get_credentials() reads, so a client can authenticate a download without persisting
anything to disk. (Kept on the deployment branch; the PR branch uses the client-sent path.)

* feat(api): gate per-request CDM override behind serve.cdm_overrides

A per-request `cdm` selects a server-side device, so honour it only when allow-listed.
`serve.cdm_overrides` opts in: a list permits those device names, or `true` permits any
(single trusted client). Unset/false rejects every override with 403, so an arbitrary device
can't be selected by default.

* fix(api): redact credentials and proxy userinfo in serialized job parameters

Job parameters can carry a raw user:pass credential and a proxy URL with embedded userinfo;
mask them wherever parameters are serialized for an API response so secrets don't leak via
the job-detail endpoint. Also read skipped-subtitle / download-failure state from the dl
instance instead of scraping stdout, and drop the dead n_m3u8dl percent branch.

* feat(api): prefer explicit AUTH_METHODS class var over source inference in /services

Inferring auth methods from authenticate() source mostly returns both options because services
call super().authenticate(cookies, credential). Prefer an explicit AUTH_METHODS class var when a
service declares one, falling back to inference.

* style: use plain hyphens instead of em-dashes in comments

* feat(api): gate per-job credentials, isolate caches, scrub error fields

Address review feedback on #113:
- Gate per-request credential/credentials behind serve.allow_job_credentials (default off,
  403 when not opted in), mirroring the existing serve.cdm_overrides CDM gate.
- Isolate the token cache per credential: when a per-job credential is set, namespace
  config.directories.cache by its hash in the worker, so two clients on the same service
  with different credentials can't share a cached session.
- Scrub the credential, its password half, and proxy userinfo out of error_message,
  error_details, error_traceback and worker_stderr before they leave via the job-detail API.
- Remove the unused _execute_download_sync in-process path (would have leaked one job's
  credential into the shared global config).
- Document serve.cdm_overrides and serve.allow_job_credentials in the example config.
- Add tests for both gates (403 default, allowlist pass) and the parameter/error redaction.

* fix(dl): flag download_failed when result() swallows a worker failure

dl.result() catches a download-worker exception, reports it, and returns
without re-raising so the CLI still exits cleanly. An embedding caller (the
API worker) had no way to tell the title actually failed and would report
the job completed with no output. Expose a download_failed flag, set in the
swallow path, that the worker reads after result() returns.

* feat(api): surface skipped subtitles and pass skip_subtitle_errors

Thread skip_subtitle_errors from the job into dl() so the API can opt into
non-fatal subtitle handling, and report which subtitles were skipped: store
them on the job (dl.SkippedSubtitle dicts) and include them in job details
so a client can tell the user which weren't available.

---------

Co-authored-by: Avi Cohen <avraham.coh770@gmail.com>
2026-06-08 11:38:08 -06:00
imSp4rky 79b884fb6b feat(subtitle): support 'original' sub_format to keep source format 2026-06-07 22:35:49 -06:00
imSp4rky 29232925d5 feat(subtitle): data-driven conversion registry + SubtitleEdit 5 support
Replace the hardcoded conversion if/elif in Subtitle.convert with a capability-matrix backend registry (subtitle_convert.py): each backend declares the source->target pairs it supports plus a rank, and run_conversion tries them in order as a real fallback chain. conversion_method pins a backend but still falls back (pin-then-fallback).

- Detect the cross-platform SubtitleEdit 5+ CLI (seconv) and use its --flag syntax for convert, SDH stripping, and reverse-RTL
- Protect styled ASS/SSA from automatic SRT downconversion; honor an explicit --sub-format / sidecar_format
- Read segmented fVTT (wvtt) and fTTML (stpp) directly from fragmented MP4
- Improve ASS/SSA font detection: inline \fn overrides, Format-located Fontname column, @-prefix strip, case-insensitive de-dup; covers SSA too
- Update SUBTITLE_CONFIG.md, example yaml, README; add regression tests and a backend benchmark script
2026-06-07 22:21:25 -06:00
imSp4rky e6613e8ed8 Merge branch 'dev' of https://github.com/unshackle-dl/unshackle into dev 2026-06-07 16:00:43 -06:00
imSp4rky ce0d9d8355 feat(vault): add VAULT_TAG to share key vault across services
Lets sibling services read/write one key-vault namespace instead of being tied to their own tag. New Service.VAULT_TAG class var, resolved via Services.get_vault_tag() in both the dl and serve paths. AMZN_WEB opts into the AMZN namespace; EXAMPLE documents usage.
2026-06-07 15:59:59 -06:00
sp4rk.y 27c8fcdae1 Merge pull request #116 from avi-dev-user/subtitle-nonfatal
fix(dl): make a failed subtitle non-fatal under --skip-subtitle-errors
2026-06-07 12:56:48 -06:00
imSp4rky 4a543c59e6 fix(dl): mux hybrid ingredients standalone only when range explicitly requested
-r HYBRID alone muxed the HDR10/HDR10+ base layer as a standalone output because only the ingredient DV track was flagged hybrid_base_only. The inverse was also broken: HDR10/HDR10+/DV tracks never entered the standalone-deliverable pool, so -r HYBRID,HDR10P only delivered the standalone HDR10+ by accident of the first bug.

- Add Tracks.partition_hybrid_videos: ingredient ranges (HDR10/HDR10+/DV) enter the deliverable pool only when their range is explicitly requested alongside HYBRID; replaces the duplicated filter in dl.py.
- Add Tracks.flag_hybrid_ingredients: any track in the hybrid selection but not in the deliverable selection is flagged hybrid_base_only; replaces and generalises the DV-only dv_is_deliverable special case.
2026-06-06 16:01:54 -06:00
Avi Cohen 4fdffc9435 refactor(dl): type the two-pass download helper + pin skipped_subtitles shape
Addresses review feedback on the failed-subtitle handling:
- Fully annotate download_tracks_in_passes and the download_track closure (MyPy strict).
- Replace list[str] skipped_subtitles with a documented SkippedSubtitle TypedDict
  (id + language + title) so a client can report which subtitle of which title was
  skipped; pin the shape with a contract test.
- Clear DOWNLOAD_CANCELLED in a finally so no failed track leaves it set for later code.
- Document why the subtitle pass must stay sequential (a concurrent pass would silently
  drop in-flight subtitles via the cancel event).
- Warn only when a title skipped a subtitle and produced no video/audio/subtitle (was a
  loose len(title.tracks) check that ignored chapters/attachments).
- Narrow the over-broad remove() except to ValueError with a debug log.
- Add tests: final-clear on the fatal path, all-subs-skipped keeps video/audio, and
  duplicate-language subtitles distinguished by id.
2026-06-06 09:56:29 +03:00
sp4rk.y 51fbc33979 Merge pull request #115 from avi-dev-user/clearkey-aes128
fix(hls): decrypt AES-128 (ClearKey) media-playlist keys + per-segment sequence IV
2026-06-05 16:26:09 -06:00
imSp4rky c03ff01c32 fix(core): replace deprecated ast.Num visitor in FPS parser
ast.Num/node.n deprecated since Python 3.8; NodeVisitor falls back to visit_Num with a DeprecationWarning per dispatch. Under -W error this surfaced as a misleading fps ValueError in Video.init. Replace with visit_Constant, reject non-numeric constants, and pin parse results for int/fraction/float inputs in a regression test.
2026-06-05 15:23:27 -06:00
imSp4rky 23cc8c9ec9 refactor(cli): replace deprecated click.MultiCommand with click.Group
MultiCommand is deprecated since Click 8.3 and removed in 9.0; its functionality was folded into Group, which supports the same list_commands/get_command lazy-loading overrides. Unblocks a future Click 9 bump and silences the import-time DeprecationWarning that broke test collection under -W error::DeprecationWarning.
2026-06-05 15:23:27 -06:00
sp4rk.y 6ae0fc2c81 Merge pull request #114 from unshackle-dl/dependabot/uv/aiohttp-3.14.0
chore(deps): bump aiohttp from 3.13.5 to 3.14.0
2026-06-05 15:06:12 -06:00
Avi Cohen 73d2cbccf8 style: use plain hyphens instead of em-dashes in comments 2026-06-05 18:25:14 +03:00
Avi Cohen 6a9b9238ba style: use plain hyphens instead of em-dashes in comments 2026-06-05 18:25:14 +03:00
Avi Cohen 41fef5d33a fix(dl): make a failed subtitle non-fatal under --skip-subtitle-errors
A single failing subtitle track previously aborted the whole download. Add an opt-in
--skip-subtitle-errors flag: when set, a Subtitle failure is logged and the track dropped from
the mux while the video/audio still complete (Video/Audio failures stay fatal; default
behaviour is unchanged).

Done at the right layer to avoid the shared-event race: a failed track sets the process-global
DOWNLOAD_CANCELLED event, which makes other in-flight tracks early-return without raising — so a
skipped subtitle could otherwise silently truncate the video/audio that still got muxed. The
download is split into two passes (download_tracks_in_passes): the fatal tracks download
concurrently first, then the skippable subtitles run in a separate sequential pass once nothing
else is in flight, with the event reset before each and at the start of every title. Skipped
languages are recorded on the dl instance (skipped_subtitles) for callers to surface.

Adds tests for the cancel-event interaction (a failing subtitle no longer truncates the
video/audio), the good/bad subtitle mix, the flag-off fatal path, and the per-title reset.
2026-06-04 08:06:23 +03:00
Avi Cohen 9590c54c33 fix(hls): decrypt AES-128 (ClearKey) media-playlist keys + per-segment sequence IV
The download path only wired up media-playlist keys when they were Widevine/PlayReady; an
AES-128 ClearKey was built but never assigned to session_drm, so segments were merged still
encrypted and the output was unplayable. Handle ClearKey from the media playlist (no license
needed), and when EXT-X-KEY has no explicit IV use each segment's media sequence number as
the IV (RFC 8216 5.2).
2026-06-04 07:09:25 +03:00
dependabot[bot] a79cf2b5ee chore(deps): bump aiohttp from 3.13.5 to 3.14.0
---
updated-dependencies:
- dependency-name: aiohttp
  dependency-version: 3.14.0
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-06-04 00:21:47 +00:00
32 changed files with 2154 additions and 523 deletions
+2
View File
@@ -24,6 +24,8 @@ device_private_key
device_vmp_blob
unshackle/binaries/*
!unshackle/binaries/placehere.txt
# test fixtures (binary subtitle samples) must be tracked despite the *.mp4 rule above
!tests/tracks/fixtures/*.mp4
unshackle/cache/
unshackle/cookies/
unshackle/certs/
+4
View File
@@ -47,6 +47,10 @@ External tools on your `PATH` (recommended versions):
- [Bento4](https://github.com/axiomatic-systems/Bento4) - ≥ 1.6.0-639
- [dovi_tool](https://github.com/quietvoid/dovi_tool) - ≥ 2.1
Optional:
- [SubtitleEdit](https://github.com/SubtitleEdit/subtitleedit/releases) - ≥ 5.0 (`SeConv` CLI)
## License
[GPL-3.0](LICENSE). Do not use unshackle for content you lack the rights to. Keep the core free and open; keep service code private. Be kind.
+36 -8
View File
@@ -8,17 +8,44 @@ For the canonical example, see `unshackle/unshackle-example.yaml`.
Control subtitle conversion, SDH (hearing-impaired) stripping, formatting preservation, and output behavior.
- `conversion_method`: How to convert subtitles between formats. Default: `auto`.
- `auto`: Smart routing - subby for WebVTT/fVTT/SAMI; for SSA/ASS/MicroDVD/MPL2/TMP use SubtitleEdit when available, otherwise pysubs2; standard pycaption/SubtitleEdit pipeline for everything else.
- `subby`: Always use subby with `CommonIssuesFixer` (falls back to standard if the source codec isn't supported by subby).
- `subtitleedit`: Prefer SubtitleEdit when available; otherwise fall back to the standard pycaption pipeline.
- `pycaption`: Use only the pycaption library (no SubtitleEdit, no subby). Limited to SRT, TTML, and WebVTT outputs.
- `pysubs2`: Use pysubs2 (supports SRT, SSA, ASS, WebVTT, TTML, SAMI, MicroDVD, MPL2, TMP).
- `conversion_method`: Which backend to convert subtitles with. Default: `auto`.
Routing is data-driven (`unshackle/core/tracks/subtitle_convert.py`): a registry of backends each
declares the source→target codec pairs it supports plus a preference rank. For a conversion, the
available backends that support the pair are tried in rank order — a real fallback chain. A
non-`auto` value **pins** that backend first, then still falls back through the chain if it can't
handle the pair or errors (pin-then-fallback). A service may also set `preferred_conversion_method`
on its tracks; an explicit `conversion_method` in config always wins.
- `auto`: Best available backend by rank — SubtitleEdit (if installed) for highest fidelity;
otherwise subby for WebVTT/fVTT/SAMI→SRT (adds `CommonIssuesFixer` cleanup), pysubs2 for SSA/ASS
and the broad format set, pycaption as last resort.
- `subby`: Prefer subby (`CommonIssuesFixer`); reads WebVTT/fVTT/SAMI, writes SRT (and TTML/VTT via
an SRT intermediate).
- `subtitleedit`: Prefer SubtitleEdit / `seconv`. Highest fidelity — preserves positioning/italics.
- `pycaption`: Prefer pycaption. **Flattens positioning/italics**, writes only SRT/TTML/WebVTT.
- `pysubs2`: Prefer pysubs2 (SRT, SSA, ASS, WebVTT, TTML, SAMI, MicroDVD, MPL2, TMP). The only
pure-Python backend that reads ASS/SSA, so it is the default for styled SubStation sources.
**Styled-subtitle protection**: ASS/SSA are never *automatically* downconverted to SRT (the
conversion is skipped and the original kept) — SRT cannot carry their positioning/colours/styling.
This applies to the default muxed track only; explicit requests still convert: a per-download
`--sub-format srt` for the muxed track, or `sidecar_format: srt` for sidecars. To keep raw styled
sidecars, set `sidecar_format: original`.
**Segmented subtitles** (`fVTT`/WVTT and `fTTML`/STPP from DASH/HLS, e.g. HBO Max) are read directly
from the fragmented MP4: fVTT via subby's `WVTTConverter`, fTTML via pycaption's box parsing. They
can be converted *from* but not *to*.
**SubtitleEdit on Linux/macOS**: install the SubtitleEdit 5+ CLI (`SeConv` / `seconv`, the
self-contained cross-platform build from the SubtitleEdit releases) onto `PATH` or into
`unshackle/binaries/`. unshackle targets the SubtitleEdit **5+** command syntax. The Windows
`SubtitleEdit.exe` is the GUI app — use the `SeConv` CLI binary for headless conversion.
- `sdh_method`: How to strip SDH cues. Default: `auto`.
- `auto`: Try subby for SRT first, then SubtitleEdit (when `conversion_method` is `auto`/`subtitleedit` and the binary is available), then subtitle-filter as the final fallback.
- `subby`: Use subby's `SDHStripper`. **Only operates on SRT**; for other codecs the call returns without stripping.
- `subtitleedit`: Use SubtitleEdit's `/RemoveTextForHI` when the binary is available; otherwise falls through to subtitle-filter.
- `subtitleedit`: Use SubtitleEdit's `--remove-text-for-hi` (SE5 CLI) when the binary is available; otherwise falls through to subtitle-filter.
- `filter-subs`: Use the `subtitle-filter` library directly (`rm_fonts`, `rm_ast`, `rm_music`, `rm_effects`, `rm_names`, `rm_author`).
- `strip_sdh`: Enable/disable automatic SDH stripping for tracks flagged as SDH. Default: `true`.
@@ -68,6 +95,7 @@ These behaviors are intentional and have no config knobs — they apply to every
## Related
- Filename sanitization (e.g. parenthesis handling, unidecode bracket artifacts from PR #105) lives in `unshackle/core/utilities.py::sanitize_filename` and is governed by `output_template`, not the `subtitle:` config block.
- Subtitle codec support and the conversion matrix are defined in `unshackle/core/tracks/subtitle.py`.
- Subtitle codec support is defined in `unshackle/core/tracks/subtitle.py`; the conversion backend
registry, capability matrix, and ranks live in `unshackle/core/tracks/subtitle_convert.py`.
---
+1 -1
View File
@@ -57,7 +57,7 @@ dependencies = [
"pyplayready>=0.8.3,<0.9",
"cryptography>=45.0.0,<47",
"subby",
"aiohttp>=3.13.4,<4",
"aiohttp>=3.14.0,<4",
"aiohttp-swagger3>=0.9.0,<1",
"pysubs2>=1.7.0,<2",
"PyExecJS>=1.5.1,<2",
+98
View File
@@ -0,0 +1,98 @@
#!/usr/bin/env python3
"""
Benchmark subtitle conversion backends to (re-)tune the preference ranks in
``unshackle/core/tracks/subtitle_convert.py``.
Runs every backend that can read each input file, converting to a target format (default
SRT), and reports cue count, leaked ASS override tags, and output size — so you can compare
fidelity per (source, target) pair on real files. Read-only: copies inputs to a temp dir.
Usage:
uv run python scripts/bench_subtitle_backends.py <file-or-dir> [<file-or-dir> ...] [--target SRT]
Example:
uv run python scripts/bench_subtitle_backends.py downloads/
"""
from __future__ import annotations
import argparse
import re
import shutil
import tempfile
from pathlib import Path
from unshackle.core.tracks import subtitle_convert as sc
from unshackle.core.tracks.subtitle import Subtitle
Codec = Subtitle.Codec
EXT_TO_CODEC = {
".srt": Codec.SubRip,
".vtt": Codec.WebVTT,
".ass": Codec.SubStationAlphav4,
".ssa": Codec.SubStationAlpha,
".ttml": Codec.TimedTextMarkupLang,
".smi": Codec.SAMI,
".sami": Codec.SAMI,
}
def gather(paths: list[str]) -> list[Path]:
files: list[Path] = []
for p in paths:
path = Path(p)
if path.is_dir():
files.extend(f for f in path.rglob("*") if f.suffix.lower() in EXT_TO_CODEC)
elif path.suffix.lower() in EXT_TO_CODEC:
files.append(path)
return sorted(files)
def metrics(text: str) -> tuple[int, int, int]:
cues = len(re.findall(r"-->", text))
ass_residue = len(re.findall(r"\{\\", text))
return cues, ass_residue, len(text)
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("paths", nargs="+", help="subtitle files or directories")
ap.add_argument("--target", default="SRT", help="target codec value (SRT, VTT, ASS, ...)")
args = ap.parse_args()
target = Codec(args.target.upper())
files = gather(args.paths)
if not files:
print("No subtitle files found.")
return
tmp = Path(tempfile.mkdtemp(prefix="subbench_"))
print(f"{'file':40} {'source':10} {'backend':12} {'ok':3} {'cues':>5} {'resid':>5} {'bytes':>7}")
for f in files:
source = EXT_TO_CODEC[f.suffix.lower()]
if source == target:
continue
for backend in sc.REGISTRY:
if not (backend.is_available() and backend.can_convert(source, target)):
continue
work = tmp / f"{f.stem}.{backend.name}{f.suffix}"
shutil.copy2(f, work)
sub = Subtitle(url="x", language="en", codec=source)
sub.path = work
try:
# Call the backend directly so each row reflects only that backend (no fallback).
out = work.with_suffix(f".{target.value.lower()}")
backend.convert(sub, target, out)
cues, resid, size = metrics(out.read_text("utf8", errors="replace"))
print(
f"{f.name[:40]:40} {source.name[:10]:10} {backend.name:12} {'Y':3} {cues:>5} {resid:>5} {size:>7}"
)
except Exception as e: # noqa: BLE001 - benchmark reports failures, does not raise
print(
f"{f.name[:40]:40} {source.name[:10]:10} {backend.name:12} {'N':3} {'-':>5} {'-':>5} {'-':>7} {type(e).__name__}"
)
if __name__ == "__main__":
main()
View File
+33
View File
@@ -0,0 +1,33 @@
"""Tests for SubtitleCodecChoice — notably the ``original`` keep-source sentinel that
services set via the ``sub_format`` override (must not be rejected as an invalid codec)."""
from __future__ import annotations
import pytest
from unshackle.core.tracks.subtitle import Subtitle
from unshackle.core.utils.click_types import SubtitleCodecChoice
choice = SubtitleCodecChoice(Subtitle.Codec)
@pytest.mark.parametrize("value", ["original", "ORIGINAL", "Original"])
def test_original_is_kept_as_sentinel(value):
assert choice.convert(value) == "original"
@pytest.mark.parametrize(
"value,expected",
[
("srt", Subtitle.Codec.SubRip),
("ass", Subtitle.Codec.SubStationAlphav4),
("vtt", Subtitle.Codec.WebVTT),
("WVTT", Subtitle.Codec.fVTT),
],
)
def test_codecs_still_map(value, expected):
assert choice.convert(value) == expected
def test_empty_is_none():
assert choice.convert(None) is None
+29
View File
@@ -0,0 +1,29 @@
import warnings
import pytest
from unshackle.core.utilities import FPS
@pytest.mark.parametrize(
("expr", "expected"),
[
("24", 24),
("23.976", pytest.approx(23.976)),
("30000/1001", pytest.approx(29.97, abs=0.001)),
],
)
def test_parse_pins_results_without_deprecation_warnings(expr: str, expected: object) -> None:
with warnings.catch_warnings():
warnings.simplefilter("error", DeprecationWarning)
assert FPS.parse(expr) == expected
def test_parse_rejects_non_numeric_constant() -> None:
with pytest.raises(ValueError, match="Invalid fps value"):
FPS.parse("'24'")
def test_parse_rejects_non_division_operation() -> None:
with pytest.raises(ValueError, match="Invalid operation"):
FPS.parse("24+1")
@@ -0,0 +1,152 @@
"""Unit tests for the /api/download security gates (per-request CDM + credential overrides)
and the secret redaction applied to job parameters and error/stderr fields."""
from __future__ import annotations
from datetime import datetime
import pytest
from aiohttp import web
from unshackle.core.api import handlers
from unshackle.core.api.download_manager import (DownloadJob, JobStatus, _redact_parameters, _redact_text,
_secret_values)
from unshackle.core.api.errors import APIError, APIErrorCode
pytestmark = pytest.mark.unit
# ---------- redaction ----------
def test_redact_parameters_masks_secrets_and_proxy_userinfo():
params = {
"service": "ATV",
"credential": "user:hunter2",
"password": "pw",
"token": "tok",
"api_key": "ak",
"proxy": "http://bob:secret@proxy.example:8080",
"quality": "1080p",
}
red = _redact_parameters(params)
assert red["credential"] == "***"
assert red["password"] == "***"
assert red["token"] == "***"
assert red["api_key"] == "***"
assert red["proxy"] == "http://***@proxy.example:8080"
assert red["quality"] == "1080p" # non-secret left intact
assert params["credential"] == "user:hunter2" # original dict not mutated
def test_redact_parameters_masks_credentials_dict():
assert _redact_parameters({"credentials": {"default": "u:p"}})["credentials"] == "***"
def test_secret_values_includes_password_half_and_dict_values():
secrets = _secret_values({"credential": "user:hunter2", "credentials": {"d": "alice:wonder"}})
assert "user:hunter2" in secrets # full credential
assert "hunter2" in secrets # password half of user:pass
assert "alice:wonder" in secrets # value from the credentials map
def test_redact_text_scrubs_credential_and_proxy_from_free_text():
params = {"credential": "user:hunter2", "proxy": "http://bob:secret@p:1"}
out = _redact_text("auth failed for user:hunter2 via http://bob:secret@p:1", params)
assert "hunter2" not in out
assert "bob:secret@" not in out
assert "***" in out
def test_redact_text_passthrough_without_secrets():
assert _redact_text("plain error", {}) == "plain error"
assert _redact_text(None, {}) is None
def test_to_dict_full_details_redacts_error_fields_and_parameters():
job = DownloadJob(
job_id="j1",
status=JobStatus.FAILED,
created_time=datetime(2026, 1, 1),
service="ATV",
title_id="t",
parameters={"credential": "user:hunter2"},
)
job.error_message = "login failed for user:hunter2"
job.worker_stderr = "Traceback ... user:hunter2 ..."
d = job.to_dict(include_full_details=True)
assert "hunter2" not in d["error_message"]
assert "hunter2" not in d["worker_stderr"]
assert d["parameters"]["credential"] == "***"
# ---------- gates ----------
class _PastGate(Exception):
"""Raised by the stubbed Services.load to prove a request got past the gate into the try block."""
@pytest.fixture
def stub_handler(monkeypatch):
"""Make the service valid and make the first call after the gate (Services.load) explode, so a
forbidden request raises APIError *before* the try block and an allowed one is caught inside it."""
monkeypatch.setattr(handlers, "validate_service", lambda tag, request=None: tag)
def _boom(*_args, **_kwargs):
raise _PastGate()
monkeypatch.setattr(handlers.Services, "load", _boom)
return monkeypatch
async def test_cdm_override_forbidden_by_default(stub_handler):
stub_handler.setattr(handlers.config, "serve", {})
with pytest.raises(APIError) as ei:
await handlers.download_handler({"service": "ATV", "title_id": "t", "cdm": "dev"})
assert ei.value.error_code == APIErrorCode.FORBIDDEN
async def test_cdm_override_allowed_when_enabled(stub_handler):
stub_handler.setattr(handlers.config, "serve", {"cdm_overrides": True})
# passing the gate reaches the stubbed Services.load, whose error is caught and returned as a response
resp = await handlers.download_handler({"service": "ATV", "title_id": "t", "cdm": "dev"})
assert isinstance(resp, web.Response)
async def test_cdm_override_allowlist_permits_only_named_device(stub_handler):
stub_handler.setattr(handlers.config, "serve", {"cdm_overrides": ["good"]})
assert isinstance(
await handlers.download_handler({"service": "ATV", "title_id": "t", "cdm": "good"}), web.Response
)
with pytest.raises(APIError) as ei:
await handlers.download_handler({"service": "ATV", "title_id": "t", "cdm": "other"})
assert ei.value.error_code == APIErrorCode.FORBIDDEN
async def test_credential_forbidden_by_default(stub_handler):
stub_handler.setattr(handlers.config, "serve", {})
with pytest.raises(APIError) as ei:
await handlers.download_handler({"service": "ATV", "title_id": "t", "credential": "u:p"})
assert ei.value.error_code == APIErrorCode.FORBIDDEN
async def test_credential_allowed_when_enabled(stub_handler):
stub_handler.setattr(handlers.config, "serve", {"allow_job_credentials": True})
resp = await handlers.download_handler({"service": "ATV", "title_id": "t", "credential": "u:p"})
assert isinstance(resp, web.Response)
# ---------- range validation ----------
def test_range_validation_accepts_hdr10p_and_alias():
# canonical "HDR10P" and back-compat "HDR10+" both pass; mixed casing too
assert handlers.validate_download_parameters({"range": ["HDR10P", "DV", "SDR"]}) is None
assert handlers.validate_download_parameters({"range": ["hdr10+"]}) is None
assert handlers.validate_download_parameters({"range": "HYBRID"}) is None
def test_range_validation_rejects_unknown_and_lists_hdr10p():
err = handlers.validate_download_parameters({"range": ["HDR99"]})
assert err and "HDR10P" in err and "HDR99" in err
+155
View File
@@ -0,0 +1,155 @@
"""Unit tests for the aggregate per-job download progress sink.
``build_job_progress_callables`` wraps the per-track progress callables so the API job sees one
aggregate signal - a bitrate-weighted completion percentage, track counts, and the labels of the
tracks downloading now - instead of each track's own bouncing 0-100%. These tests pin that
contract."""
from __future__ import annotations
import pytest
from unshackle.core.api.progress import (DOWNLOAD_PROGRESS_CEILING, build_job_progress_callables,
track_progress_label, track_progress_weight)
pytestmark = pytest.mark.unit
# --- lightweight track stand-ins (label/weight key off class name + attributes) ---
class _Range:
def __init__(self, value):
self.value = value
class Video:
def __init__(self, height=1080, range_value="SDR", bitrate=4_000_000):
self.height = height
self.range = _Range(range_value)
self.bitrate = bitrate
class Audio:
def __init__(self, language="en-US", channels="2.0", bitrate=200_000):
self.language = language
self.channels = channels
self.bitrate = bitrate
class Subtitle:
def __init__(self, language="fr"):
self.language = language
self.bitrate = None
def _noop(**kwargs):
pass
def test_track_progress_label():
assert track_progress_label(Video(2160, "DV")) == "video 2160p DV"
assert track_progress_label(Video(1080, "HDR10+")) == "video 1080p HDR10+"
assert track_progress_label(Audio("en-US", "5.1")) == "audio en-US 5.1"
assert track_progress_label(Subtitle("ro")) == "subtitle ro"
def test_weight_video_over_audio_over_subtitle():
assert track_progress_weight(Video(bitrate=4_000_000)) == 4_000_000
assert track_progress_weight(Audio(bitrate=200_000)) == 200_000
# subtitle has no bitrate -> small fixed weight, far below media
assert track_progress_weight(Subtitle()) < track_progress_weight(Audio(bitrate=200_000))
def test_weighting_makes_video_dominate_progress():
updates: list[dict] = []
video, sub = Video(bitrate=4_000_000), Subtitle()
cbs = build_job_progress_callables([video, sub], [_noop, _noop], updates.append)
# subtitle fully done, video untouched -> progress is tiny (subtitle barely weighted)
cbs[1](downloaded="Downloaded")
assert updates[-1]["completed_tracks"] == 1
assert updates[-1]["progress"] < 5.0
# video half done -> progress is dominated by video (scaled into the 0..ceiling download band)
cbs[0](total=100, completed=50)
assert updates[-1]["progress"] > 40.0
def test_active_tracks_labels_reported_and_cleared_on_done():
updates: list[dict] = []
cbs = build_job_progress_callables(
[Video(2160, "DV"), Audio("en-US", "2.0")], [_noop, _noop], updates.append
)
cbs[0](total=100, completed=10) # video downloading
assert updates[-1]["active_tracks"] == ["video 2160p DV"]
assert updates[-1]["phase"] == "downloading video 2160p DV"
cbs[1](total=100, completed=10) # audio also downloading
assert updates[-1]["active_tracks"] == ["video 2160p DV", "audio en-US 2.0"]
cbs[0](downloaded="Downloaded") # video done -> drops out of active
assert updates[-1]["active_tracks"] == ["audio en-US 2.0"]
def test_aggregate_progress_is_monotonic_with_counts():
updates: list[dict] = []
inner_calls = [0, 0, 0]
def make_inner(i):
def inner(**kwargs):
inner_calls[i] += 1
return inner
tracks = [Video(bitrate=1000), Audio(bitrate=1000), Subtitle()]
cbs = build_job_progress_callables(tracks, [make_inner(0), make_inner(1), make_inner(2)], updates.append)
assert len(cbs) == 3
cbs[0](total=100, completed=50)
cbs[0](downloaded="Downloaded")
cbs[1](total=100, completed=50)
progresses = [u["progress"] for u in updates]
assert progresses == sorted(progresses)
assert updates[-1]["completed_tracks"] == 1
assert updates[-1]["total_tracks"] == 3
assert inner_calls == [2, 1, 0]
def test_all_tracks_done_reaches_download_ceiling():
# Downloads fill up to the ceiling; dl.result drives muxing the rest of the way to 100.
updates: list[dict] = []
cbs = build_job_progress_callables([Audio(bitrate=1000), Audio(bitrate=1000)], [_noop, _noop], updates.append)
cbs[0](total=10, completed=10, downloaded="Downloaded")
assert updates[-1]["progress"] < DOWNLOAD_PROGRESS_CEILING
assert updates[-1]["completed_tracks"] == 1
cbs[1](total=10, completed=10, downloaded="Decrypted")
assert updates[-1]["progress"] == pytest.approx(DOWNLOAD_PROGRESS_CEILING)
assert updates[-1]["completed_tracks"] == 2
def test_finished_track_does_not_dip_when_callable_reused_for_decrypt():
"""A track hits 100% (then decrypt reuses the callable with completed=0); the aggregate must
hold, never dip - even before the terminal 'Downloaded'/'Decrypted' string arrives."""
updates: list[dict] = []
cbs = build_job_progress_callables([Video(bitrate=1000), Video(bitrate=1000)], [_noop, _noop], updates.append)
cbs[0](total=100, completed=100) # download hits 100% BEFORE any terminal string -> 50%
cbs[0](total=200, completed=0) # decrypt phase resets counts, still no terminal string
cbs[0](total=200, completed=100) # decrypt mid-way
cbs[0](total=200, completed=200, downloaded="Decrypted") # terminal
progresses = [u["progress"] for u in updates]
assert progresses == sorted(progresses) # monotonic, no dip
assert updates[-1]["progress"] == pytest.approx(DOWNLOAD_PROGRESS_CEILING / 2)
assert updates[-1]["completed_tracks"] == 1
def test_skipped_subtitle_counts_as_done():
updates: list[dict] = []
cbs = build_job_progress_callables([Subtitle()], [_noop], updates.append)
cbs[0](downloaded="[yellow]SKIPPED")
assert updates[-1]["completed_tracks"] == 1
assert updates[-1]["progress"] == pytest.approx(DOWNLOAD_PROGRESS_CEILING)
Binary file not shown.
+94 -3
View File
@@ -6,10 +6,14 @@ Covers the selection primitives that back `-r ...,DV,HYBRID` downloads:
single lowest DV track used as a hybrid ingredient.
- ``Tracks.merge_video_selections`` — de-duplicates the ingredient/deliverable
overlap so a DV track that is chosen as both is not muxed/downloaded twice.
- ``Tracks.partition_hybrid_videos`` — splits the ladder into hybrid-ingredient
candidates and the standalone-deliverable pool; HDR10/HDR10+/DV only enter
the pool when their range was explicitly requested alongside HYBRID.
- ``Tracks.flag_hybrid_ingredients`` — marks ingredient-only tracks with
``hybrid_base_only`` so the standalone mux loop skips them.
The full ``dl`` selection pipeline (range filtering, the ``dv_is_deliverable``
partition, the ``hybrid_base_only`` ingredient flag and the standalone mux loop)
is orchestration glue inside the Click command; these tests lock down the pure
The remaining ``dl`` glue (the Cartesian deliverable product and the mux loop)
is orchestration inside the Click command; these tests lock down the pure
units it relies on plus the documented end-state of a realistic ATV-style ladder.
"""
@@ -137,6 +141,93 @@ def test_merge_dedup_uses_track_identity_by_id() -> None:
assert len(Tracks.merge_video_selections([a], [b])) == 1
# ---------------------------------------------------------------------------
# partition_hybrid_videos
# ---------------------------------------------------------------------------
def test_partition_hybrid_only_keeps_ingredients_out_of_pool(ladder: list[Video]) -> None:
"""`-r HYBRID`: HDR10+/DV are ingredients only; pool holds just SDR."""
candidates, pool = Tracks.partition_hybrid_videos(ladder, [])
assert ids(candidates) == {"hdr10p-2160", "hdr10p-1080", "dv-2160", "dv-1080", "dv-360"}
assert ids(pool) == {"sdr-2160", "sdr-1080-avc", "sdr-1080-hevc"}
def test_partition_admits_hdr10p_to_pool_when_requested(ladder: list[Video]) -> None:
"""`-r HYBRID,HDR10P`: HDR10+ tracks become standalone deliverable candidates."""
candidates, pool = Tracks.partition_hybrid_videos(ladder, [Video.Range.HDR10P])
assert {"hdr10p-2160", "hdr10p-1080"} <= ids(pool)
assert not any(t.range == Video.Range.DV for t in pool)
# Candidates are unaffected by the requested ranges.
assert ids(candidates) == {"hdr10p-2160", "hdr10p-1080", "dv-2160", "dv-1080", "dv-360"}
def test_partition_admits_dv_and_hdr10p_when_both_requested(ladder: list[Video]) -> None:
"""`-r HYBRID,HDR10P,DV`: both ranges enter the deliverable pool."""
_, pool = Tracks.partition_hybrid_videos(ladder, [Video.Range.HDR10P, Video.Range.DV])
assert {"hdr10p-2160", "hdr10p-1080", "dv-2160", "dv-1080", "dv-360"} <= ids(pool)
def test_partition_hdr10_requested_does_not_admit_hdr10p() -> None:
H = Video.Codec.HEVC
tracks = [
make_video("hdr10-2160", range_=Video.Range.HDR10, height=2160, bitrate=20_000_000, codec=H),
make_video("hdr10p-2160", range_=Video.Range.HDR10P, height=2160, bitrate=20_000_000, codec=H),
]
_, pool = Tracks.partition_hybrid_videos(tracks, [Video.Range.HDR10])
assert ids(pool) == {"hdr10-2160"}
# ---------------------------------------------------------------------------
# flag_hybrid_ingredients
# ---------------------------------------------------------------------------
def flagged(tracks: list[Video]) -> set[str]:
return {t.id for t in tracks if t.hybrid_base_only}
def test_flag_hybrid_only_flags_base_and_ingredient_dv(ladder: list[Video]) -> None:
"""`-r HYBRID`: no deliverables, so the base and the ingredient DV are both
skipped by the standalone mux loop — only the hybrid output remains."""
hybrid_selected = list(filter(Tracks().select_hybrid(ladder, [1080]), ladder))
Tracks.flag_hybrid_ingredients(hybrid_selected, [])
assert flagged(ladder) == {"hdr10p-1080", "dv-360"}
def test_flag_hybrid_plus_hdr10p_keeps_base_deliverable(ladder: list[Video]) -> None:
"""`-r HYBRID,HDR10P`: the base is also an explicit deliverable, only the
ingredient DV is skipped — hybrid + standalone HDR10+ are muxed."""
hybrid_selected = list(filter(Tracks().select_hybrid(ladder, [1080]), ladder))
base = next(t for t in ladder if t.id == "hdr10p-1080")
Tracks.flag_hybrid_ingredients(hybrid_selected, [base])
assert flagged(ladder) == {"dv-360"}
def test_flag_hybrid_plus_hdr10p_and_dv_keeps_both_deliverables(ladder: list[Video]) -> None:
"""`-r HYBRID,HDR10P,DV`: best DV is a deliverable, lowest DV stays
ingredient-only — hybrid + HDR10+ + DV are muxed."""
hybrid_selected = list(filter(Tracks().select_hybrid(ladder, [1080]), ladder))
base = next(t for t in ladder if t.id == "hdr10p-1080")
best_dv = next(t for t in ladder if t.id == "dv-1080")
Tracks.flag_hybrid_ingredients(hybrid_selected, [base, best_dv])
assert flagged(ladder) == {"dv-360"}
def test_flag_single_dv_rendition_as_deliverable_stays_unflagged() -> None:
"""`-r HYBRID,DV` with one DV rendition: the same track is ingredient and
deliverable, so it must still be muxed standalone."""
H = Video.Codec.HEVC
tracks = [
make_video("hdr10p-1080", range_=Video.Range.HDR10P, height=1080, bitrate=9_000_000, codec=H),
make_video("dv-1080", range_=Video.Range.DV, height=1080, bitrate=9_000_000, codec=H),
]
hybrid_selected = list(filter(Tracks().select_hybrid(tracks, [1080]), tracks))
dv = next(t for t in tracks if t.id == "dv-1080")
Tracks.flag_hybrid_ingredients(hybrid_selected, [dv])
assert flagged(tracks) == {"hdr10p-1080"}
# ---------------------------------------------------------------------------
# documented end-state for the reported command
# ---------------------------------------------------------------------------
+314
View File
@@ -0,0 +1,314 @@
"""Tests for the data-driven subtitle conversion registry (``tracks/subtitle_convert.py``).
Covers three things the refactor must guarantee:
- the capability matrix resolves the right backend chain per (source, target) and env
(SubtitleEdit present or not),
- ``conversion_method`` pins a backend but still falls back (pin-then-fallback),
- styled SubStation (ASS/SSA) is never auto-downconverted to SRT unless explicitly forced.
Backends pysubs2/subby/pycaption are hard deps so the conversion paths run in CI without
SubtitleEdit; SubtitleEdit availability is simulated by patching ``binaries.SubtitleEdit``.
"""
from __future__ import annotations
import pathlib
import re
import struct
import pytest
from unshackle.core import binaries
from unshackle.core.tracks import subtitle_convert as sc
from unshackle.core.tracks.subtitle import Subtitle
Codec = Subtitle.Codec
VTT_SAMPLE = """WEBVTT
1
00:00:01.000 --> 00:00:02.000
Hello
2
00:00:03.000 --> 00:00:04.000
World
"""
ASS_SAMPLE = """[Script Info]
ScriptType: v4.00+
[V4+ Styles]
Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
Style: Default,Arial,20,&H00FFFFFF,&H000000FF,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,2,1,2,10,10,18,1
[Events]
Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
Dialogue: 0,0:00:01.00,0:00:02.00,Default,,0,0,0,,{\\i1}Hello{\\i0}
Dialogue: 0,0:00:03.00,0:00:04.00,Default,,0,0,0,,World
"""
@pytest.fixture(autouse=True)
def _no_subtitleedit(monkeypatch):
"""Default every test to a SubtitleEdit-less environment; tests opt in when needed."""
monkeypatch.setattr(binaries, "SubtitleEdit", None)
def make_sub(tmp_path, name: str, text: str, codec: Codec) -> Subtitle:
path = tmp_path / name
path.write_text(text, encoding="utf8")
sub = Subtitle(url="https://example.test/x", language="en", codec=codec)
sub.path = path
return sub
def cue_count(path) -> int:
return len(re.findall(r"-->", path.read_text("utf8")))
# --- capability matrix / resolver -------------------------------------------------------
def test_resolve_webvtt_to_srt_order():
chain = [b.name for b in sc.resolve_backends(Codec.WebVTT, Codec.SubRip)]
assert chain == ["subby", "pysubs2", "pycaption"]
def test_resolve_ass_to_srt_only_pysubs2_without_subtitleedit():
# subby and pycaption cannot read ASS, so only pysubs2 remains.
chain = [b.name for b in sc.resolve_backends(Codec.SubStationAlphav4, Codec.SubRip)]
assert chain == ["pysubs2"]
def test_subtitleedit_ranks_first_when_available(monkeypatch):
monkeypatch.setattr(binaries, "SubtitleEdit", "/usr/bin/seconv")
chain = [b.name for b in sc.resolve_backends(Codec.WebVTT, Codec.SubRip)]
assert chain[0] == "subtitleedit"
def test_pin_then_fallback_orders_pin_first():
chain = [b.name for b in sc.resolve_backends(Codec.WebVTT, Codec.SubRip, pin="pysubs2")]
assert chain[0] == "pysubs2"
assert "subby" in chain # fallbacks remain after the pin
def test_pin_unavailable_falls_back_to_ranked_chain():
# subtitleedit pinned but not installed -> just the ranked available backends.
chain = [b.name for b in sc.resolve_backends(Codec.WebVTT, Codec.SubRip, pin="subtitleedit")]
assert chain == ["subby", "pysubs2", "pycaption"]
def test_fallback_runs_when_first_backend_fails(tmp_path, monkeypatch):
monkeypatch.setattr("unshackle.core.config.config.subtitle", {}, raising=False)
def boom(self, source, src, target, out):
raise RuntimeError("backend exploded")
# WebVTT->SRT chain is [subby, pysubs2, pycaption]; kill subby, expect pysubs2 to finish.
monkeypatch.setattr(sc.SubbyBackend, "convert", boom)
sub = make_sub(tmp_path, "x.vtt", VTT_SAMPLE, Codec.WebVTT)
out = sub.convert(Codec.SubRip, forced=True)
assert sub.codec == Codec.SubRip
assert cue_count(out) == 2
def test_no_backend_for_unsupported_target_raises(tmp_path):
sub = make_sub(tmp_path, "x.ass", ASS_SAMPLE, Codec.SubStationAlphav4)
with pytest.raises(NotImplementedError):
sub.convert(Codec.fVTT, forced=True) # no backend writes segmented fVTT
# --- styled-ASS protection --------------------------------------------------------------
def test_ass_to_srt_kept_as_is_when_not_forced(tmp_path, monkeypatch):
monkeypatch.setattr("unshackle.core.config.config.subtitle", {}, raising=False)
sub = make_sub(tmp_path, "x.ass", ASS_SAMPLE, Codec.SubStationAlphav4)
out = sub.convert(Codec.SubRip, forced=False)
assert sub.codec == Codec.SubStationAlphav4 # unchanged
assert out == sub.path
assert out.suffix == ".ass"
def test_ass_to_srt_converts_when_forced(tmp_path, monkeypatch):
monkeypatch.setattr("unshackle.core.config.config.subtitle", {}, raising=False)
sub = make_sub(tmp_path, "x.ass", ASS_SAMPLE, Codec.SubStationAlphav4)
out = sub.convert(Codec.SubRip, forced=True)
assert sub.codec == Codec.SubRip
assert out.suffix == ".srt"
assert cue_count(out) == 2
assert "{\\" not in out.read_text("utf8") # override tags stripped
# --- conversion paths -------------------------------------------------------------------
def test_webvtt_to_srt_conversion(tmp_path, monkeypatch):
monkeypatch.setattr("unshackle.core.config.config.subtitle", {}, raising=False)
sub = make_sub(tmp_path, "x.vtt", VTT_SAMPLE, Codec.WebVTT)
out = sub.convert(Codec.SubRip, forced=True)
assert sub.codec == Codec.SubRip
assert cue_count(out) == 2
def test_same_codec_is_noop(tmp_path):
sub = make_sub(tmp_path, "x.srt", "1\n00:00:01,000 --> 00:00:02,000\nHi\n", Codec.SubRip)
assert sub.convert(Codec.SubRip) == sub.path
assert sub.codec == Codec.SubRip
# --- ASS/SSA font detection ------------------------------------------------------------
FONT_ASS = """[Script Info]
ScriptType: v4.00+
[V4+ Styles]
Format: Name, Fontname, Fontsize, PrimaryColour, Bold, Italic, Alignment, MarginV, Encoding
Style: Default,Trebuchet MS,24,&H00FFFFFF,0,0,2,18,1
Style: sign,@Arial Unicode MS,20,&H00FFFFFF,0,0,8,10,1
[Events]
Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
Dialogue: 0,0:00:01.00,0:00:02.00,Default,,0,0,0,,{\\fnTimes New Roman}A sign
Dialogue: 0,0:00:03.00,0:00:04.00,Default,,0,0,0,,{\\fntimes new roman}lower case
Dialogue: 0,0:00:05.00,0:00:06.00,Default,,0,0,0,,{\\fnGeorgia\\b1}bold note
"""
def test_extract_fonts_styles_and_inline_overrides():
fonts = Subtitle.extract_fonts(FONT_ASS)
# Style fontnames (column located via Format line, @-prefix stripped) + inline \fn overrides
assert fonts == {"Trebuchet MS", "Arial Unicode MS", "Times New Roman", "Georgia"}
# case-insensitive de-dup keeps the mixed-case spelling, not "times new roman"
assert "times new roman" not in fonts
def test_extract_fonts_handles_non_default_column_order():
ass = (
"[V4+ Styles]\n"
"Format: Name, Fontsize, Fontname, Bold\n" # Fontname not in the usual position
"Style: Main,28,Verdana,0\n"
)
assert Subtitle.extract_fonts(ass) == {"Verdana"}
# --- non-Latin scripts (RTL / CJK) preserved through conversion ------------------------
CJK_RTL_VTT = """WEBVTT
1
00:00:01.000 --> 00:00:02.000
مرحبا بالعالم
2
00:00:03.000 --> 00:00:04.000
안녕하세요
3
00:00:05.000 --> 00:00:06.000
你好世界
"""
@pytest.mark.parametrize(
"pattern",
[r"[؀-ۿ]", r"[가-힣]", r"[一-鿿]"], # Arabic, Hangul, CJK
)
def test_non_latin_scripts_survive_vtt_to_srt(tmp_path, monkeypatch, pattern):
monkeypatch.setattr("unshackle.core.config.config.subtitle", {}, raising=False)
sub = make_sub(tmp_path, "x.vtt", CJK_RTL_VTT, Codec.WebVTT)
out = sub.convert(Codec.SubRip, forced=True)
text = out.read_text("utf8")
assert cue_count(out) == 3
assert re.search(pattern, text) # script survived the round-trip, no mojibake
# --- SDH stripping ----------------------------------------------------------------------
SDH_SRT = """1
00:00:01,000 --> 00:00:02,000
[door creaks]
2
00:00:03,000 --> 00:00:04,000
Hello there.
3
00:00:05,000 --> 00:00:06,000
♪ upbeat music ♪
"""
def test_sdh_stripping_removes_effects_keeps_dialogue(tmp_path, monkeypatch):
# subby's SDHStripper runs on SRT without SubtitleEdit installed.
monkeypatch.setattr("unshackle.core.config.config.subtitle", {"sdh_method": "subby"}, raising=False)
sub = make_sub(tmp_path, "x.srt", SDH_SRT, Codec.SubRip)
sub.strip_hearing_impaired()
out = sub.path.read_text("utf8")
assert "Hello there." in out # real dialogue kept
assert "door creaks" not in out # bracketed effect removed (subby SDHStripper)
# --- segmented (box-encapsulated) formats: fVTT (wvtt) / fTTML (stpp) --------------------
# These ship from DASH/HLS as fragmented MP4 (e.g. HBO Max). The downloader concatenates
# init + media segments into one file; parse() reads the MP4 boxes directly.
FIXTURES = pathlib.Path(__file__).parent / "fixtures"
def caption_total(caption_set) -> int:
return sum(len(caption_set.get_captions(lang)) for lang in caption_set.get_languages())
def build_stpp_mp4(*ttml_fragments: str) -> bytes:
"""A minimal stpp-style MP4: ftyp + one mdat per TTML fragment (what fTTML.parse reads)."""
def box(box_type: bytes, payload: bytes) -> bytes:
return struct.pack(">I", 8 + len(payload)) + box_type + payload
data = box(b"ftyp", b"isom" + struct.pack(">I", 0) + b"isomiso6")
for frag in ttml_fragments:
data += box(b"mdat", frag.encode("utf8"))
return data
def test_segmented_fvtt_parses_and_converts(tmp_path, monkeypatch):
monkeypatch.setattr("unshackle.core.config.config.subtitle", {}, raising=False)
data = (FIXTURES / "segmented.wvtt.mp4").read_bytes()
caption_set = Subtitle.parse(data, Codec.fVTT)
assert caption_total(caption_set) == 2
seg = tmp_path / "seg.wvtt"
seg.write_bytes(data)
sub = Subtitle(url="https://example.test/x", language="en", codec=Codec.fVTT)
sub.path = seg
# download() converts fVTT -> WebVTT (not "forced"); chain is subby then pycaption.
out = sub.convert(Codec.WebVTT)
assert sub.codec == Codec.WebVTT
assert cue_count(out) == 2
def test_segmented_fttml_parses_and_converts(tmp_path, monkeypatch):
monkeypatch.setattr("unshackle.core.config.config.subtitle", {}, raising=False)
frag = (
'<?xml version="1.0" encoding="utf-8"?>'
'<tt xmlns="http://www.w3.org/ns/ttml" xml:lang="en"><body><div>'
'<p begin="00:00:0{a}.000" end="00:00:0{b}.000">Line {a}</p>'
"</div></body></tt>"
)
data = build_stpp_mp4(frag.format(a=1, b=2), frag.format(a=3, b=4))
caption_set = Subtitle.parse(data, Codec.fTTML)
assert caption_total(caption_set) == 2
seg = tmp_path / "seg.stpp"
seg.write_bytes(data)
sub = Subtitle(url="https://example.test/x", language="en", codec=Codec.fTTML)
sub.path = seg
# download() converts fTTML -> TTML (only pycaption can read fTTML); then -> SRT.
sub.convert(Codec.TimedTextMarkupLang)
assert sub.codec == Codec.TimedTextMarkupLang
out = sub.convert(Codec.SubRip, forced=True)
assert cue_count(out) == 2
+193
View File
@@ -0,0 +1,193 @@
"""Tests for ``download_tracks_in_passes`` - the two-pass track download used by
``dl.result()`` when ``--skip-subtitle-errors`` is set.
The behaviour under test is the cancel-event interaction: a failed track sets the
process-global ``DOWNLOAD_CANCELLED`` event, which makes other in-flight tracks
early-return without raising. Running the fatal video/audio tracks to completion
*before* the skippable subtitles removes that race, so a subtitle failure can no
longer truncate the video/audio that still gets muxed.
"""
from __future__ import annotations
import pytest
from unshackle.commands.dl import SkippedSubtitle, download_tracks_in_passes
from unshackle.core.constants import DOWNLOAD_CANCELLED
from unshackle.core.tracks import Audio, Subtitle, Video
def make_video(track_id: str = "v") -> Video:
return Video(
id_=track_id,
url=f"https://example.test/{track_id}.m3u8",
language="en",
codec=Video.Codec.AVC,
range_=Video.Range.SDR,
width=1920,
height=1080,
bitrate=5_000_000,
)
def make_audio(track_id: str = "a") -> Audio:
return Audio(
id_=track_id,
url=f"https://example.test/{track_id}.m3u8",
language="en",
codec=Audio.Codec.AAC,
bitrate=128_000,
)
def make_subtitle(track_id: str, language: str) -> Subtitle:
return Subtitle(
id_=track_id,
url=f"https://example.test/{track_id}.vtt",
language=language,
codec=Subtitle.Codec.WebVTT,
)
class Harness:
"""Mimics how ``dl.result`` drives the helper, with a controllable downloader.
``run_one`` mirrors ``Track.download``: it early-returns (without recording a
completion) when the cancel event is already set, and a track flagged to fail
sets the event and raises - exactly what the real cancel sites do.
"""
def __init__(self, fail_ids: set[str]):
self.fail_ids = fail_ids
self.completed: list[str] = []
self.early_returned: list[str] = []
self.skipped: list[Subtitle] = []
def run_one(self, track, _index):
if DOWNLOAD_CANCELLED.is_set():
self.early_returned.append(track.id)
return
if track.id in self.fail_ids:
DOWNLOAD_CANCELLED.set()
raise RuntimeError(f"{track.id} failed")
self.completed.append(track.id)
def on_subtitle_skipped(self, track):
self.skipped.append(track)
@pytest.fixture(autouse=True)
def _clear_event():
DOWNLOAD_CANCELLED.clear()
yield
DOWNLOAD_CANCELLED.clear()
def test_failed_subtitle_does_not_truncate_video_or_audio():
"""A subtitle that fails *and sets the cancel event* must not stop the video/audio."""
video, audio = make_video(), make_audio()
sub = make_subtitle("s-he", "he")
h = Harness(fail_ids={"s-he"})
download_tracks_in_passes(
[video, audio, sub], 4, h.run_one,
skip_subtitle_errors=True, on_subtitle_skipped=h.on_subtitle_skipped,
)
assert set(h.completed) == {"v", "a"} # both fatal tracks fully downloaded
assert h.early_returned == [] # nothing early-returned because of the subtitle
assert h.skipped == [sub] # the subtitle was recorded as skipped
def test_good_subtitle_kept_bad_subtitle_skipped():
video = make_video()
good, bad = make_subtitle("s-en", "en"), make_subtitle("s-fr", "fr")
h = Harness(fail_ids={"s-fr"})
download_tracks_in_passes(
[video, good, bad], 4, h.run_one,
skip_subtitle_errors=True, on_subtitle_skipped=h.on_subtitle_skipped,
)
assert "s-en" in h.completed # the available subtitle still downloaded
assert h.skipped == [bad] # only the failing one was skipped
def test_subtitle_failure_stays_fatal_without_flag():
"""Default behaviour (flag off) is unchanged: a subtitle failure aborts the title."""
video = make_video()
sub = make_subtitle("s-he", "he")
h = Harness(fail_ids={"s-he"})
with pytest.raises(RuntimeError):
download_tracks_in_passes(
[video, sub], 4, h.run_one,
skip_subtitle_errors=False, on_subtitle_skipped=h.on_subtitle_skipped,
)
assert not DOWNLOAD_CANCELLED.is_set() # the finally clears the event even on the fatal path
def test_cancel_event_is_reset_between_titles():
"""A cancel left set by a previous title must not skip this title's tracks."""
DOWNLOAD_CANCELLED.set()
video, audio = make_video(), make_audio()
h = Harness(fail_ids=set())
download_tracks_in_passes(
[video, audio], 4, h.run_one,
skip_subtitle_errors=True, on_subtitle_skipped=h.on_subtitle_skipped,
)
assert set(h.completed) == {"v", "a"}
assert h.early_returned == []
def test_cancel_event_cleared_after_failed_final_subtitle():
"""A subtitle failing in the last pass leaves the event clear on exit, not set."""
video = make_video()
sub = make_subtitle("s-he", "he")
h = Harness(fail_ids={"s-he"})
download_tracks_in_passes(
[video, sub], 4, h.run_one,
skip_subtitle_errors=True, on_subtitle_skipped=h.on_subtitle_skipped,
)
assert not DOWNLOAD_CANCELLED.is_set() # the helper clears it on exit for any later code
def test_all_subtitles_skipped_video_audio_kept():
"""Every subtitle failing must not stop the video/audio, and each is recorded."""
video, audio = make_video(), make_audio()
s1, s2 = make_subtitle("s-en", "en"), make_subtitle("s-he", "he")
h = Harness(fail_ids={"s-en", "s-he"})
download_tracks_in_passes(
[video, audio, s1, s2], 4, h.run_one,
skip_subtitle_errors=True, on_subtitle_skipped=h.on_subtitle_skipped,
)
assert set(h.completed) == {"v", "a"} # both fatal tracks survived
assert {t.id for t in h.skipped} == {"s-en", "s-he"} # every failing subtitle recorded
def test_duplicate_language_subtitles_distinguished_by_id():
"""Forced + SDH share a language; a failure of each must be distinguishable by track id -
the reason ``SkippedSubtitle`` carries ``id`` and not just ``language``."""
forced, sdh = make_subtitle("en-forced", "en"), make_subtitle("en-sdh", "en")
h = Harness(fail_ids={"en-forced", "en-sdh"})
download_tracks_in_passes(
[make_video(), forced, sdh], 4, h.run_one,
skip_subtitle_errors=True, on_subtitle_skipped=h.on_subtitle_skipped,
)
assert [t.id for t in h.skipped] == ["en-forced", "en-sdh"] # same language, distinct ids
def test_skipped_subtitle_contract():
"""Pin the public ``skipped_subtitles`` entry shape - #113 serializes it into the job, so a
field rename/removal here is a breaking change and must fail a test."""
assert set(SkippedSubtitle.__annotations__) == {"id", "language", "title"}
assert SkippedSubtitle.__required_keys__ == frozenset({"id", "language", "title"})
+169 -83
View File
@@ -11,6 +11,7 @@ import shutil
import subprocess
import sys
import time
from collections.abc import Iterable
from concurrent import futures
from concurrent.futures import ThreadPoolExecutor
from copy import deepcopy
@@ -19,7 +20,7 @@ from http.cookiejar import CookieJar, MozillaCookieJar
from itertools import product
from pathlib import Path
from threading import Lock
from typing import Any, Callable, Optional
from typing import Any, Callable, Optional, TypedDict, Union
from uuid import UUID
import click
@@ -42,7 +43,7 @@ from unshackle.core.cdm import DecryptLabsRemoteCDM
from unshackle.core.cdm.detect import is_playready_cdm, is_widevine_cdm
from unshackle.core.config import config
from unshackle.core.console import console
from unshackle.core.constants import DOWNLOAD_LICENCE_ONLY, AnyTrack, context_settings
from unshackle.core.constants import DOWNLOAD_CANCELLED, DOWNLOAD_LICENCE_ONLY, AnyTrack, context_settings
from unshackle.core.credential import Credential
from unshackle.core.drm import DRM_T, MonaLisa, PlayReady, Widevine
from unshackle.core.events import events
@@ -70,6 +71,59 @@ from unshackle.core.utils.subprocess import ffprobe
from unshackle.core.vaults import Vaults
class SkippedSubtitle(TypedDict):
"""A subtitle skipped under ``--skip-subtitle-errors``. Accumulated as ``dl.skipped_subtitles``,
one entry per track; ``id`` and ``title`` identify which subtitle of which title was unavailable."""
id: str
language: str
title: str
def download_tracks_in_passes(
tracks: Iterable[AnyTrack],
max_concurrent: int,
run_one: Callable[[AnyTrack, int], None],
*,
skip_subtitle_errors: bool,
on_subtitle_skipped: Callable[[Subtitle], None],
) -> None:
"""Download a title's tracks so a skippable subtitle failure can't corrupt the rest.
A failed track sets the process-global ``DOWNLOAD_CANCELLED`` event, making other in-flight
tracks early-return without raising. With ``skip_subtitle_errors`` set, video/audio download
concurrently first; the subtitles then run one at a time (a concurrent pass would let one
failure's cancel silently drop the others, unrecorded), with the event cleared before each.
Video/audio failures stay fatal. The event is cleared on entry (stale cancel from a prior
title) and in ``finally`` (never leave it set for later code).
``run_one(track, index)`` downloads a single track; ``on_subtitle_skipped(track)`` records a
subtitle whose download raised (handled here).
"""
DOWNLOAD_CANCELLED.clear()
indexed = list(enumerate(tracks))
if skip_subtitle_errors:
primary = [(i, t) for i, t in indexed if not isinstance(t, Subtitle)]
skippable = [(i, t) for i, t in indexed if isinstance(t, Subtitle)]
else:
primary, skippable = indexed, []
try:
with ThreadPoolExecutor(max_concurrent) as pool:
future_to_track = {pool.submit(run_one, track, i): track for i, track in primary}
for download in futures.as_completed(future_to_track):
download.result() # a video/audio failure is fatal
for i, track in skippable:
DOWNLOAD_CANCELLED.clear()
try:
run_one(track, i)
except Exception:
on_subtitle_skipped(track)
finally:
DOWNLOAD_CANCELLED.clear() # never leave a failed track's cancel set for later code
class dl:
@staticmethod
def truncate_pssh_for_display(pssh_string: str, drm_type: str) -> str:
@@ -257,7 +311,7 @@ class dl:
)
temp_sub.path = temp_path
try:
temp_sub.convert(target_codec)
temp_sub.convert(target_codec, forced=True)
if temp_sub.path and temp_sub.path.exists():
shutil.copy2(temp_sub.path, sidecar_path)
finally:
@@ -467,13 +521,20 @@ class dl:
"--sub-format",
type=SubtitleCodecChoice(Subtitle.Codec),
default=None,
help="Set Output Subtitle Format, only converting if necessary.",
help="Set Output Subtitle Format, only converting if necessary. Use 'original' to keep source format.",
)
@click.option("-V", "--video-only", is_flag=True, default=False, help="Only download video tracks.")
@click.option("-A", "--audio-only", is_flag=True, default=False, help="Only download audio tracks.")
@click.option("-S", "--subs-only", is_flag=True, default=False, help="Only download subtitle tracks.")
@click.option("-C", "--chapters-only", is_flag=True, default=False, help="Only download chapter markers.")
@click.option("-ns", "--no-subs", is_flag=True, default=False, help="Do not download subtitle tracks.")
@click.option(
"--skip-subtitle-errors",
is_flag=True,
default=False,
help="If a subtitle track fails to download, skip it and continue instead of "
"aborting the whole title (video/audio failures stay fatal).",
)
@click.option("-na", "--no-audio", is_flag=True, default=False, help="Do not download audio tracks.")
@click.option("-nc", "--no-chapters", is_flag=True, default=False, help="Do not download chapter markers.")
@click.option("-nv", "--no-video", is_flag=True, default=False, help="Do not download video tracks.")
@@ -609,6 +670,13 @@ class dl:
self.log = logging.getLogger("download")
self.completed_files: list[Path] = []
# Subtitles skipped under --skip-subtitle-errors, recorded so an embedding caller can
# report which weren't available without parsing the console output. See SkippedSubtitle.
self.skipped_subtitles: list[SkippedSubtitle] = []
# result() catches a download-worker failure, reports it, and returns rather than
# re-raising (so the CLI still exits cleanly). Flag it so an embedding caller (the API
# worker) can tell the title did not complete instead of reading it as a success.
self.download_failed: bool = False
if not config.output_template:
raise click.ClickException(
@@ -618,6 +686,7 @@ class dl:
)
self.service = Services.get_tag(ctx.invoked_subcommand)
self.vault_service = Services.get_vault_tag(self.service)
service_dl_config = config.services.get(self.service, {}).get("dl", {})
if service_dl_config:
param_types = {param.name: param.type for param in ctx.command.params if param.name}
@@ -818,7 +887,7 @@ class dl:
cdm_only = ctx.params.get("cdm_only")
if cdm_only:
self.vaults = Vaults(self.service)
self.vaults = Vaults(self.vault_service)
self.log.info("CDM-only mode: Skipping vault loading")
if self.debug_logger:
self.debug_logger.log(
@@ -829,7 +898,7 @@ class dl:
)
else:
with console.status("Loading Key Vaults...", spinner="dots"):
self.vaults = Vaults(self.service)
self.vaults = Vaults(self.vault_service)
total_vaults = len(config.key_vaults)
failed_vaults = []
@@ -1045,12 +1114,13 @@ class dl:
require_subs: list[str],
forced_subs: bool,
exact_lang: bool,
sub_format: Optional[Subtitle.Codec],
sub_format: Optional[Union[Subtitle.Codec, str]],
video_only: bool,
audio_only: bool,
subs_only: bool,
chapters_only: bool,
no_subs: bool,
skip_subtitle_errors: bool,
no_audio: bool,
no_chapters: bool,
no_video: bool,
@@ -1073,6 +1143,7 @@ class dl:
split_audio: Optional[bool] = None,
real_video_bitrate: bool = False,
real_audio_bitrate: bool = False,
progress_sink: Optional[Callable[[dict[str, Any]], None]] = None,
*_: Any,
**__: Any,
) -> None:
@@ -1697,24 +1768,12 @@ class dl:
has_hybrid = any(r == Video.Range.HYBRID for r in range_)
non_hybrid_ranges = [r for r in range_ if r != Video.Range.HYBRID]
# DV is both a hybrid ingredient (lowest track) and, when explicitly
# requested, a standalone deliverable (best track per resolution).
dv_is_deliverable = Video.Range.DV in non_hybrid_ranges
if quality:
missing_resolutions = []
if has_hybrid:
hybrid_candidate_tracks = [
v
for v in title.tracks.videos
if v.range in (Video.Range.HDR10, Video.Range.HDR10P, Video.Range.DV)
]
non_hybrid_tracks = [
v
for v in title.tracks.videos
if v.range not in (Video.Range.HDR10, Video.Range.HDR10P, Video.Range.DV)
or (dv_is_deliverable and v.range == Video.Range.DV)
]
hybrid_candidate_tracks, non_hybrid_tracks = Tracks.partition_hybrid_videos(
title.tracks.videos, non_hybrid_ranges
)
hybrid_filter = title.tracks.select_hybrid(hybrid_candidate_tracks, quality, worst=worst)
hybrid_selected = list(filter(hybrid_filter, hybrid_candidate_tracks))
@@ -1757,17 +1816,9 @@ class dl:
pre_hybrid_videos: list[Video] = list(title.tracks.videos) if has_hybrid else []
if has_hybrid:
# Apply hybrid selection for HYBRID tracks
hybrid_candidate_tracks = [
v
for v in title.tracks.videos
if v.range in (Video.Range.HDR10, Video.Range.HDR10P, Video.Range.DV)
]
non_hybrid_tracks = [
v
for v in title.tracks.videos
if v.range not in (Video.Range.HDR10, Video.Range.HDR10P, Video.Range.DV)
or (dv_is_deliverable and v.range == Video.Range.DV)
]
hybrid_candidate_tracks, non_hybrid_tracks = Tracks.partition_hybrid_videos(
title.tracks.videos, non_hybrid_ranges
)
if not quality:
best_resolution = max((v.height for v in hybrid_candidate_tracks), default=None)
@@ -1811,14 +1862,10 @@ class dl:
title.tracks.videos = Tracks.merge_video_selections(hybrid_selected, non_hybrid_selected)
# Flag the lowest DV track as ingredient-only so mux skips it standalone,
# unless it is itself the chosen DV deliverable (single DV rendition).
selected_dv = [v for v in title.tracks.videos if v.range == Video.Range.DV]
if selected_dv:
ingredient_dv = min(selected_dv, key=lambda v: v.height)
deliverable_dv = [v for v in non_hybrid_selected if v.range == Video.Range.DV]
if not (dv_is_deliverable and ingredient_dv in deliverable_dv):
ingredient_dv.hybrid_base_only = True
# Flag tracks selected only as hybrid ingredients (the HDR base and/or
# the lowest DV) so the standalone mux loop skips them. Tracks also
# picked as explicit deliverables stay unflagged.
Tracks.flag_hybrid_ingredients(hybrid_selected, non_hybrid_selected)
else:
selected_videos: list[Video] = []
if video_multi_lang:
@@ -2168,6 +2215,13 @@ class dl:
selected_tracks, tracks_progress_callables = title.tracks.tree(add_progress=True)
if progress_sink is not None:
from unshackle.core.api.progress import build_job_progress_callables
tracks_progress_callables = build_job_progress_callables(
list(title.tracks), tracks_progress_callables, progress_sink
)
for track in title.tracks:
if hasattr(track, "needs_drm_loading") and track.needs_drm_loading:
track.load_drm_if_needed(service)
@@ -2205,41 +2259,64 @@ class dl:
try:
with Live(Padding(download_table, (1, 5)), console=console, refresh_per_second=5):
with ThreadPoolExecutor(downloads) as pool:
for download in futures.as_completed(
(
pool.submit(
track.download,
session=track.session or service.session,
no_proxy_download=no_proxy_download,
prepare_drm=partial(
partial(self.prepare_drm, table=download_table),
track=track,
title=title,
certificate=partial(
service.get_widevine_service_certificate,
title=title,
track=track,
),
licence=partial(
service.get_playready_license
if is_playready_cdm(self.cdm)
else service.get_widevine_license,
title=title,
track=track,
),
cdm_only=cdm_only,
vaults_only=vaults_only,
export=export_path,
),
cdm=self.cdm,
max_workers=workers,
progress=tracks_progress_callables[i],
)
for i, track in enumerate(title.tracks)
)
):
download.result()
def download_track(track: AnyTrack, i: int) -> None:
track.download(
session=track.session or service.session,
no_proxy_download=no_proxy_download,
prepare_drm=partial(
partial(self.prepare_drm, table=download_table),
track=track,
title=title,
certificate=partial(
service.get_widevine_service_certificate,
title=title,
track=track,
),
licence=partial(
service.get_playready_license
if is_playready_cdm(self.cdm)
else service.get_widevine_license,
title=title,
track=track,
),
cdm_only=cdm_only,
vaults_only=vaults_only,
export=export_path,
),
cdm=self.cdm,
max_workers=workers,
progress=tracks_progress_callables[i],
)
def on_subtitle_skipped(track: Subtitle) -> None:
lang = str(track.language)
self.log.warning(f"Subtitle {lang} failed to download, skipping it.")
self.skipped_subtitles.append(SkippedSubtitle(id=track.id, language=lang, title=str(title)))
try:
title.tracks.subtitles.remove(track)
except ValueError:
self.log.debug(f"Skipped subtitle {track.id} was already absent from the track list.")
skipped_before = len(self.skipped_subtitles)
download_tracks_in_passes(
title.tracks,
downloads,
download_track,
skip_subtitle_errors=skip_subtitle_errors,
on_subtitle_skipped=on_subtitle_skipped,
)
if (
len(self.skipped_subtitles) > skipped_before
and not title.tracks.videos
and not title.tracks.audio
and not title.tracks.subtitles
):
self.log.warning(
f"{title}: all subtitles were skipped and no video or audio was "
"downloaded - nothing was produced for this title."
)
except KeyboardInterrupt:
console.print(Padding(":x: Download Cancelled...", (0, 5, 1, 5)))
@@ -2253,6 +2330,9 @@ class dl:
)
return
except Exception as e: # noqa
# Reported and swallowed (no re-raise) so the CLI exits cleanly; flag it so the
# API worker sees the title failed rather than completing with no output.
self.download_failed = True
error_messages = [
":x: Download Failed...",
f" {type(e).__name__}: {e}",
@@ -2304,20 +2384,20 @@ class dl:
with console.status("Converting Subtitles..."):
for subtitle in title.tracks.subtitles:
if sub_format == "original":
continue
if sub_format:
if subtitle.codec != sub_format:
subtitle.convert(sub_format)
subtitle.convert(sub_format, forced=True)
elif subtitle.codec == Subtitle.Codec.TimedTextMarkupLang:
# MKV does not support TTML, VTT is the next best option
subtitle.convert(Subtitle.Codec.WebVTT)
with console.status("Checking Subtitles for Fonts..."):
font_names = []
font_names: list[str] = []
for subtitle in title.tracks.subtitles:
if subtitle.codec == Subtitle.Codec.SubStationAlphav4:
for line in subtitle.path.read_text("utf8").splitlines():
if line.startswith("Style: "):
font_names.append(line.removeprefix("Style: ").split(",")[1].strip())
if subtitle.codec in (Subtitle.Codec.SubStationAlpha, Subtitle.Codec.SubStationAlphav4):
font_names.extend(Subtitle.extract_fonts(subtitle.path.read_text("utf8")))
font_count, missing_fonts = self.attach_subtitle_fonts(font_names, title, temp_font_files)
@@ -2398,6 +2478,8 @@ class dl:
break
# Now repack the decrypted tracks
if progress_sink and any(getattr(t, "needs_repack", False) for t in title.tracks):
progress_sink({"phase": "repackaging", "progress": 92.0, "status": "downloading", "active_tracks": []})
with console.status("Repackaging tracks with FFMPEG..."):
has_repacked = False
for track in title.tracks:
@@ -2564,6 +2646,8 @@ class dl:
for video_track in title.tracks.videos or [None]:
mux_video_standalone(video_track)
if progress_sink:
progress_sink({"phase": "muxing", "progress": 96.0, "status": "downloading", "active_tracks": []})
try:
with Live(Padding(progress, (0, 5, 1, 5)), console=console):
mux_index = 0
@@ -3390,7 +3474,9 @@ class dl:
Now supports quality-based selection when quality is provided.
Raises a ValueError if there's a problem getting a CDM.
"""
cdm_name = config.cdm.get(service) or config.cdm.get("default")
# A per-request override (set by the REST API per job) takes precedence over the
# global config, so a job can select a specific CDM device without mutating shared state.
cdm_name = getattr(self, "cdm_override", None) or config.cdm.get(service) or config.cdm.get("default")
if not cdm_name:
return None
+135 -23
View File
@@ -22,6 +22,60 @@ def _sanitize_log(value: object) -> str:
return str(value).replace("\n", "").replace("\r", "").replace("\x00", "")
# Job parameters may carry secrets (a raw "user:pass" credential, a proxy URL with embedded
# userinfo). These must never leave the process via the API or logs, so they are masked
# wherever parameters are serialized for a response.
_REDACTED = "***"
_SENSITIVE_PARAM_KEYS = ("credential", "credentials", "password", "token", "api_key")
_PROXY_USERINFO_RE = re.compile(r"(?<=://)[^/@]+@")
def _redact_parameters(parameters: Dict[str, Any]) -> Dict[str, Any]:
"""Return a copy of job parameters with secrets masked, safe to serialize."""
if not isinstance(parameters, dict):
return parameters
redacted = dict(parameters)
for key in _SENSITIVE_PARAM_KEYS:
if redacted.get(key):
redacted[key] = _REDACTED
proxy = redacted.get("proxy")
if isinstance(proxy, str) and "@" in proxy:
redacted["proxy"] = _PROXY_USERINFO_RE.sub(f"{_REDACTED}@", proxy)
return redacted
def _secret_values(parameters: Dict[str, Any]) -> List[str]:
"""Raw secret strings carried in job parameters, longest first, for scrubbing free text."""
if not isinstance(parameters, dict):
return []
secrets: List[str] = []
for key in ("credential", "password", "token", "api_key"):
value = parameters.get(key)
if isinstance(value, str) and value:
secrets.append(value)
if key == "credential" and ":" in value:
password = value.split(":", 1)[1]
if len(password) >= 4: # short passwords would blanket-replace and garble the text
secrets.append(password)
creds = parameters.get("credentials")
if isinstance(creds, dict):
secrets.extend(v for v in creds.values() if isinstance(v, str) and v)
elif isinstance(creds, str) and creds:
secrets.append(creds)
return sorted(set(secrets), key=len, reverse=True) # longest first so substrings don't survive
def _redact_text(text: Optional[str], parameters: Dict[str, Any]) -> Optional[str]:
"""Mask proxy userinfo and any known parameter secrets that leaked into a free-text field
(error message / details / traceback / worker stderr) before it is returned via the API."""
if not isinstance(text, str) or not text:
return text
text = _PROXY_USERINFO_RE.sub(f"{_REDACTED}@", text)
for secret in _secret_values(parameters):
text = text.replace(secret, _REDACTED)
return text
class JobStatus(Enum):
QUEUED = "queued"
DOWNLOADING = "downloading"
@@ -54,6 +108,16 @@ class DownloadJob:
error_traceback: Optional[str] = None
worker_stderr: Optional[str] = None
# Current phase, track counts, and labels of the tracks downloading now.
phase: Optional[str] = None
completed_tracks: int = 0
total_tracks: int = 0
active_tracks: List[str] = field(default_factory=list)
# Subtitles skipped under skip_subtitle_errors (non-fatal). Each entry is a dl.SkippedSubtitle
# dict (id / language / title) so a client can report which weren't available.
skipped_subtitles: List[Dict[str, Any]] = field(default_factory=list)
# Cancellation support
cancel_event: threading.Event = field(default_factory=threading.Event)
@@ -66,20 +130,27 @@ class DownloadJob:
"service": self.service,
"title_id": self.title_id,
"progress": self.progress,
"phase": self.phase,
"completed_tracks": self.completed_tracks,
"total_tracks": self.total_tracks,
"active_tracks": self.active_tracks,
"skipped_subtitles": self.skipped_subtitles,
}
if include_full_details:
# Error/stderr/traceback are free text a service may have echoed a credential or proxy
# URL into, so scrub them with the same secrets that _redact_parameters masks.
result.update(
{
"parameters": self.parameters,
"parameters": _redact_parameters(self.parameters),
"started_time": self.started_time.isoformat() if self.started_time else None,
"completed_time": self.completed_time.isoformat() if self.completed_time else None,
"output_files": self.output_files,
"error_message": self.error_message,
"error_details": self.error_details,
"error_message": _redact_text(self.error_message, self.parameters),
"error_details": _redact_text(self.error_details, self.parameters),
"error_code": self.error_code,
"error_traceback": self.error_traceback,
"worker_stderr": self.worker_stderr,
"error_traceback": _redact_text(self.error_traceback, self.parameters),
"worker_stderr": _redact_text(self.worker_stderr, self.parameters),
}
)
@@ -110,6 +181,7 @@ def _perform_download(
import yaml
from unshackle.commands.dl import dl
from unshackle.core.api.errors import APIError, APIErrorCode
from unshackle.core.config import config
from unshackle.core.services import Services
from unshackle.core.tracks import Subtitle, Video
@@ -118,6 +190,16 @@ def _perform_download(
log.info(f"Starting sync download for job {job_id}")
# A service caches tokens under cache/<Service>/, keyed by service name only, so two jobs on
# one service with different credentials would share a cache. When a per-job credential is set,
# namespace the cache dir by a hash of it so the sessions can't cross.
job_credential = params.get("credential")
if job_credential:
import hashlib
cred_hash = hashlib.sha256(job_credential.encode("utf-8")).hexdigest()[:12]
config.directories.cache = config.directories.cache / "_jobs" / cred_hash
# Convert string parameters to enums (API receives strings, dl.result() expects enums)
vcodec_raw = params.get("vcodec")
if vcodec_raw:
@@ -224,6 +306,19 @@ def _perform_download(
enrich=params.get("enrich", False),
output_dir=Path(params["output_dir"]) if params.get("output_dir") else None,
)
# Per-request CDM override (a device name in the WVDs dir); get_cdm() takes it first.
if params.get("cdm"):
dl_instance.cdm_override = params["cdm"]
# Per-request credential ("user:pass"); feed it into the map get_credentials() reads so a
# client can authenticate without anything being persisted to disk. Without a profile,
# get_credentials() falls back to "default", so store it there too rather than dropping it
# (which would silently authenticate as the server's own default account).
if params.get("credential"):
svc_creds = config.credentials.get(service)
if not isinstance(svc_creds, dict):
config.credentials[service] = svc_creds = {}
svc_creds[params.get("profile") or "default"] = params["credential"]
service_module = Services.load(service)
@@ -271,23 +366,16 @@ def _perform_download(
stdout_capture = StringIO()
stderr_capture = StringIO()
# Simple progress tracking if callback provided
# The progress_sink (dl.build_job_progress_callables) owns the percentage; status changes
# are emitted here.
if progress_callback:
# Report initial progress
progress_callback({"progress": 0.0, "status": "starting"})
# Simple approach: report progress at key points
original_result = dl_instance.result
def result_with_progress(*args, **kwargs):
try:
# Report that download started
progress_callback({"progress": 5.0, "status": "downloading"})
# Call original method
progress_callback({"status": "downloading"})
result = original_result(*args, **kwargs)
# Report completion
progress_callback({"progress": 100.0, "status": "completed"})
return result
except Exception as e:
@@ -326,6 +414,7 @@ def _perform_download(
subs_only=params.get("subs_only", False),
chapters_only=params.get("chapters_only", False),
no_subs=params.get("no_subs", False),
skip_subtitle_errors=params.get("skip_subtitle_errors", False),
no_audio=params.get("no_audio", False),
no_chapters=params.get("no_chapters", False),
no_video=params.get("no_video", False),
@@ -346,6 +435,7 @@ def _perform_download(
worst=params.get("worst", False),
best_available=params.get("best_available", False),
split_audio=params.get("split_audio"),
progress_sink=progress_callback,
)
except SystemExit as exc:
@@ -355,7 +445,7 @@ def _perform_download(
log.error(f"Download exited with code {exc.code}")
log.error(f"Stdout: {stdout_str}")
log.error(f"Stderr: {stderr_str}")
raise Exception(f"Download failed with exit code {exc.code}")
raise APIError(APIErrorCode.DOWNLOAD_ERROR, f"Download failed with exit code {exc.code}")
except Exception as exc: # noqa: BLE001 - propagate to caller
stdout_str = stdout_capture.getvalue()
@@ -365,6 +455,18 @@ def _perform_download(
log.error(f"Stderr: {stderr_str}")
raise
# dl.result() catches a download-worker exception, reports it, but returns normally (exit 0).
# It sets download_failed in that case, so the job isn't reported as completed with no output.
if getattr(dl_instance, "download_failed", False):
detail = (stdout_capture.getvalue() + stderr_capture.getvalue())[-200:].strip()
raise APIError(APIErrorCode.WORKER_ERROR, "download worker failed: " + (detail or "see logs"))
# Surface any subtitles that were skipped (non-fatal failures) so the client can report them.
if progress_callback:
skipped_subs = getattr(dl_instance, "skipped_subtitles", None)
if skipped_subs:
progress_callback({"skipped_subtitles": list(skipped_subs)})
output_files = [str(p) for p in dl_instance.completed_files]
log.info(f"Download completed for job {job_id}, {len(output_files)} file(s) in {original_download_dir}")
@@ -647,6 +749,16 @@ class DownloadQueueManager:
if os.path.exists(progress_path):
with open(progress_path, "r", encoding="utf-8") as handle:
progress_data = json.load(handle)
if progress_data.get("phase") and progress_data["phase"] != job.phase:
job.phase = progress_data["phase"]
if progress_data.get("total_tracks"):
job.total_tracks = int(progress_data["total_tracks"])
if progress_data.get("completed_tracks") is not None:
job.completed_tracks = int(progress_data["completed_tracks"])
if "active_tracks" in progress_data:
job.active_tracks = list(progress_data["active_tracks"])
if progress_data.get("skipped_subtitles"):
job.skipped_subtitles = progress_data["skipped_subtitles"]
if "progress" in progress_data:
new_progress = float(progress_data["progress"])
if new_progress != job.progress:
@@ -670,14 +782,18 @@ class DownloadQueueManager:
stdout = stdout_bytes.decode("utf-8", errors="ignore")
stderr = stderr_bytes.decode("utf-8", errors="ignore")
# A service can echo a credential or a proxy URL into its output, so scrub it before
# it reaches the log as well, not only the API response.
safe_stdout = _redact_text(stdout.strip(), job.parameters)
safe_stderr = _redact_text(stderr.strip(), job.parameters)
if stdout.strip():
log.debug(f"Worker stdout for job {job.job_id}: {stdout.strip()}")
log.debug(f"Worker stdout for job {job.job_id}: {safe_stdout}")
if stderr.strip():
job.worker_stderr = stderr.strip()
if returncode != 0:
log.warning(f"Worker stderr for job {job.job_id}: {stderr.strip()}")
log.warning(f"Worker stderr for job {job.job_id}: {safe_stderr}")
else:
log.debug(f"Worker stderr for job {job.job_id}: {stderr.strip()}")
log.debug(f"Worker stderr for job {job.job_id}: {safe_stderr}")
result_data: Optional[Dict[str, Any]] = None
try:
@@ -719,10 +835,6 @@ class DownloadQueueManager:
except OSError:
pass
def _execute_download_sync(self, job: DownloadJob) -> List[str]:
"""Execute download synchronously using existing dl.py logic."""
return _perform_download(job.job_id, job.service, job.title_id, job.parameters.copy(), job.cancel_event)
async def _cleanup_worker(self):
"""Worker that periodically cleans up old jobs."""
while not self._shutdown_event.is_set():
+35 -8
View File
@@ -957,13 +957,13 @@ def validate_download_parameters(data: Dict[str, Any]) -> Optional[str]:
return "Cannot use both s_lang and require_subs"
if "range" in data and data["range"]:
valid_ranges = ["SDR", "HDR10", "HDR10+", "DV", "HLG", "HYBRID"]
if isinstance(data["range"], list):
for r in data["range"]:
if r.upper() not in valid_ranges:
return f"Invalid range value: {r}. Must be one of: {', '.join(valid_ranges)}"
elif data["range"].upper() not in valid_ranges:
return f"Invalid range value: {data['range']}. Must be one of: {', '.join(valid_ranges)}"
# "HDR10P" is the canonical range value ("+" is awkward in scripts); "HDR10+" stays valid.
valid_ranges = ["SDR", "HDR10", "HDR10P", "DV", "HLG", "HYBRID"]
accepted = {*valid_ranges, "HDR10+"}
values = data["range"] if isinstance(data["range"], list) else [data["range"]]
for r in values:
if r.upper() not in accepted:
return f"Invalid range value: {r}. Must be one of: {', '.join(valid_ranges)}"
return None
@@ -1005,6 +1005,32 @@ async def download_handler(data: Dict[str, Any], request: Optional[web.Request]
details={"service": normalized_service, "title_id": title_id},
)
# A per-request `cdm` selects a server-side device, so it is gated here rather than honoured
# blindly. `serve.cdm_overrides` opts in: a list permits only those device names, or `true`
# permits any (for a single trusted client). Unset/false rejects every override.
requested_cdm = data.get("cdm")
if requested_cdm:
allowed = (config.serve or {}).get("cdm_overrides")
permitted = allowed is True or (
isinstance(allowed, (list, tuple, set)) and requested_cdm in allowed
)
if not permitted:
raise APIError(
APIErrorCode.FORBIDDEN,
"The requested CDM is not permitted for API downloads.",
details={"cdm": requested_cdm},
)
# A per-request `credential` (or `credentials` map) authenticates the job with client-supplied
# secrets instead of the server-side credentials. Gate it behind `serve.allow_job_credentials`
# (default off) so a default deployment stays locked to its own credentials; mirrors the CDM gate.
if data.get("credential") or data.get("credentials"):
if not (config.serve or {}).get("allow_job_credentials"):
raise APIError(
APIErrorCode.FORBIDDEN,
"Per-request credentials are not permitted for API downloads.",
)
try:
# Load service module to extract service-specific parameter defaults
service_module = Services.load(normalized_service)
@@ -2009,9 +2035,10 @@ def _resolve_device_name(user_config: dict, drm_type: str, service_tag: str = ""
def _load_server_vaults(service_name: str) -> Any:
"""Load server vaults from config.key_vaults."""
from unshackle.core.config import config as app_config
from unshackle.core.services import Services
from unshackle.core.vaults import Vaults
vaults = Vaults(service_name)
vaults = Vaults(Services.get_vault_tag(service_name))
for vault_config in app_config.key_vaults:
cfg = vault_config.copy()
vault_type = cfg.pop("type", None)
+118
View File
@@ -0,0 +1,118 @@
"""Aggregate job-level download progress for the REST API.
Turns the per-track progress callables from ``Tracks.tree`` into one signal a job can report:
a bitrate-weighted percentage, track counts, and the labels of the tracks downloading now.
"""
from __future__ import annotations
from typing import Any, Callable
from unshackle.core.constants import AnyTrack
JOB_PROGRESS_TERMINAL_STATES = {"Downloaded", "Decrypted", "[yellow]SKIPPED"}
# Weight for a track with no bitrate (subtitles); small vs media bitrates so subs barely move the bar.
SUBTITLE_PROGRESS_WEIGHT = 50_000.0
# Downloads fill 0..this; dl.result drives the remainder (repackaging, muxing) up to 100.
DOWNLOAD_PROGRESS_CEILING = 90.0
def track_progress_label(track: AnyTrack) -> str:
"""Short label for a track, e.g. "video 2160p DV", "audio en-US 5.1", "subtitle fr"."""
track_type = type(track).__name__
if track_type == "Video":
parts = ["video"]
height = getattr(track, "height", None)
if height:
parts.append(f"{height}p")
track_range = getattr(track, "range", None)
if track_range is not None:
parts.append(track_range.value)
return " ".join(parts)
if track_type == "Audio":
parts = ["audio"]
language = getattr(track, "language", None)
if language:
parts.append(str(language))
channels = getattr(track, "channels", None)
if channels:
parts.append(str(channels))
return " ".join(parts)
if track_type == "Subtitle":
language = getattr(track, "language", None)
return f"subtitle {language}" if language else "subtitle"
return track_type.lower()
def track_progress_weight(track: AnyTrack) -> float:
"""Track weight in the aggregate (its bitrate in bits/s), so video/audio dominate subtitles."""
bitrate = getattr(track, "bitrate", None)
return float(bitrate) if bitrate else SUBTITLE_PROGRESS_WEIGHT
def build_job_progress_callables(
tracks: list[AnyTrack],
inner_callables: list[Callable[..., None]],
sink: Callable[[dict[str, Any]], None],
) -> list[Callable[..., None]]:
"""Wrap each track's progress callable so ``sink`` receives aggregate job progress.
The sink gets a bitrate-weighted mean completion across all tracks, ``completed_tracks`` /
``total_tracks`` counts, and ``active_tracks`` labels. Each track's fraction is monotonic, so
the percentage only climbs. The original ``inner`` callable is always invoked.
"""
total = len(inner_callables)
weights = [track_progress_weight(t) for t in tracks]
labels = [track_progress_label(t) for t in tracks]
total_weight = sum(weights) or 1.0
fractions = [0.0] * total
done = [False] * total
started = [False] * total
def emit() -> None:
completed = sum(done)
# Downloads fill 0..DOWNLOAD_PROGRESS_CEILING; dl.result drives muxing up to 100.
progress = sum(w * f for w, f in zip(weights, fractions)) * DOWNLOAD_PROGRESS_CEILING / total_weight
active = [labels[i] for i in range(total) if started[i] and not done[i]]
if active:
phase = "downloading " + ", ".join(active[:3])
if len(active) > 3:
phase += f" (+{len(active) - 3} more)"
else:
phase = f"downloading {completed}/{total} tracks"
sink(
{
"progress": progress,
"phase": phase,
"completed_tracks": completed,
"total_tracks": total,
"active_tracks": active,
"status": "downloading",
}
)
def wrap(index: int, inner: Callable[..., None]) -> Callable[..., None]:
counts = {"completed": 0.0, "total": 0.0}
def tee(*args: Any, **kwargs: Any) -> None:
started[index] = True
if kwargs.get("total"):
counts["total"] = kwargs["total"]
if kwargs.get("completed") is not None:
counts["completed"] = kwargs["completed"]
if "advance" in kwargs:
counts["completed"] += kwargs["advance"]
if kwargs.get("downloaded") in JOB_PROGRESS_TERMINAL_STATES:
done[index] = True
fractions[index] = 1.0
elif counts["total"]:
# max() keeps the fraction monotonic across the download->decrypt callable reuse.
fractions[index] = max(fractions[index], min(1.0, counts["completed"] / counts["total"]))
emit()
return inner(*args, **kwargs)
return tee
return [wrap(i, inner) for i, inner in enumerate(inner_callables)]
+35
View File
@@ -221,6 +221,41 @@ async def services(request: web.Request) -> web.Response:
if service_module.__doc__:
service_data["help"] = service_module.__doc__.strip()
# Capability flags, derived from which Service hooks the service overrides.
from unshackle.core.service import Service as _BaseService
service_data["needs_auth"] = (
getattr(service_module, "authenticate", None) is not _BaseService.authenticate
)
service_data["has_search"] = getattr(service_module, "search", None) is not _BaseService.search
service_data["has_drm"] = (
getattr(service_module, "get_widevine_license", None) is not _BaseService.get_widevine_license
or getattr(service_module, "get_playready_license", None) is not _BaseService.get_playready_license
)
# Prefer the service's explicit AUTH_METHODS; otherwise infer from authenticate().
methods = []
if service_data["needs_auth"]:
declared = getattr(service_module, "AUTH_METHODS", None)
if declared:
methods = list(declared)
else:
try:
import inspect as _inspect
src_lines = _inspect.getsource(service_module.authenticate).splitlines()
start = next((i + 1 for i, ln in enumerate(src_lines) if ln.rstrip().endswith(":")), 1)
body = "\n".join(src_lines[start:])
if "cookies" in body:
methods.append("cookies")
if "credential" in body:
methods.append("credentials")
except (OSError, TypeError):
pass
if not methods:
methods = ["cookies"]
service_data["auth_methods"] = methods
except Exception as e:
log.warning(f"Could not load details for service {tag}: {e}")
+1 -1
View File
@@ -37,7 +37,7 @@ def find(*names: str) -> Optional[Path]:
FFMPEG = find("ffmpeg")
FFProbe = find("ffprobe")
FFPlay = find("ffplay")
SubtitleEdit = find("SubtitleEdit")
SubtitleEdit = find("SubtitleEdit", "seconv") # seconv = cross-platform subtitleedit-cli (.NET 8)
ShakaPackager = find(
"shaka-packager",
"packager",
+1 -1
View File
@@ -59,7 +59,7 @@ def check_load_errors() -> None:
raise click.ClickException(f"Failed to load {len(LOAD_ERRORS)} command(s):\n{joined}")
class Commands(click.MultiCommand):
class Commands(click.Group):
"""Lazy-loaded command group of project commands."""
def list_commands(self, ctx: click.Context) -> list[str]:
+18
View File
@@ -570,6 +570,14 @@ class HLS:
DOWNLOAD_CANCELLED.set() # skip pending track downloads
progress(downloaded="[red]FAILED")
raise
elif isinstance(media_drm, ClearKey):
# AES-128 (ClearKey) needs no license server - the key is already fetched.
# Without this branch session_drm stayed None and segments were never
# decrypted (they were merged still-encrypted, producing a broken file).
track.drm = [media_drm]
session_drm = media_drm
initial_drm_key = media_playlist_key
initial_drm_licensed = True
# Fall back to session DRM if media playlist has no matching keys
if not initial_drm_licensed and session_drm and isinstance(session_drm, (Widevine, PlayReady)):
@@ -682,6 +690,9 @@ class HLS:
name_len = len(str(total_segments))
discon_i = 0
range_offset = 0
# First segment's Media Sequence Number - used as the AES-128 IV when EXT-X-KEY has
# no explicit IV (RFC 8216 §5.2), where each segment's IV is its sequence number.
media_sequence_start = getattr(master, "media_sequence", None) or 0
map_data: Optional[tuple[m3u8.model.InitializationSection, bytes]] = None
if session_drm:
encryption_data: Optional[tuple[Optional[m3u8.Key], DRM_T]] = (initial_drm_key, session_drm)
@@ -760,7 +771,14 @@ class HLS:
else:
# with other drm we must decrypt separately and then merge them
# for aes this is because each segment likely has 16-byte padding
key_obj = encryption_data[0]
# AES-128 with no explicit IV: each segment's IV is its media sequence
# number (RFC 8216 §5.2). Without this the engine used a zero IV and the
# output decrypted to garbage.
seq_iv = isinstance(drm, ClearKey) and not (key_obj and key_obj.iv)
for file in files:
if seq_iv and file.stem.isdigit():
drm.iv = (media_sequence_start + int(file.stem)).to_bytes(16, "big")
drm.decrypt(file)
merge(to=merged_path, via=files, delete=True, include_map_data=True)
+5
View File
@@ -93,6 +93,11 @@ class Service(metaclass=ABCMeta):
# Abstract class variables
ALIASES: tuple[str, ...] = () # list of aliases for the service; alternatives to the service tag.
GEOFENCE: tuple[str, ...] = () # list of ip regions required to use the service. empty list == no specific region.
# vault namespace override; when set, key vault read/write uses this tag instead of the service's own.
VAULT_TAG: Optional[str] = None
# Auth methods the service accepts ("cookies"/"credentials"); when None the REST /services
# endpoint infers them from authenticate().
AUTH_METHODS: Optional[tuple[str, ...]] = None
def __init__(self, ctx: click.Context):
console.print(Padding(Rule(f"[rule.text]Service: {self.__class__.__name__}"), (1, 2)))
+15 -1
View File
@@ -76,7 +76,7 @@ def check_load_errors() -> None:
raise click.ClickException(f"Failed to load {len(LOAD_ERRORS)} service(s):\n{joined}")
class Services(click.MultiCommand):
class Services(click.Group):
"""Lazy-loaded command group of project services."""
_remote_services_cache: list[dict] | None = None
@@ -274,5 +274,19 @@ class Services(click.MultiCommand):
raise KeyError(f"There is no Service added by the Tag '{tag}'")
@staticmethod
def get_vault_tag(name: str) -> str:
"""Resolve the key-vault namespace tag for a service.
Returns the service's VAULT_TAG override when set, otherwise its own tag.
Falls back to the resolved tag for non-local services (remote/import).
"""
tag = Services.get_tag(name)
try:
service = Services.load(tag)
except KeyError:
return tag
return getattr(service, "VAULT_TAG", None) or tag
__all__ = ("Services",)
+67 -325
View File
@@ -11,13 +11,12 @@ from pathlib import Path
from typing import Any, Callable, Iterable, Optional, Union
import pycaption
import pysubs2
import requests
from construct import Container
from pycaption import Caption, CaptionList, CaptionNode, WebVTTReader
from pycaption.geometry import Layout
from pymp4.parser import MP4
from subby import CommonIssuesFixer, SAMIConverter, SDHStripper, WebVTTConverter, WVTTConverter
from subby import CommonIssuesFixer, SAMIConverter, SDHStripper
from subtitle_filter import Subtitles
from unshackle.core import binaries
@@ -600,306 +599,73 @@ class Subtitle(Track):
return "\n".join(sanitized_lines)
def convert_with_subby(self, codec: Subtitle.Codec) -> Path:
def convert(self, codec: Subtitle.Codec, *, forced: bool = False) -> Path:
"""
Convert subtitle using subby library for better format support and processing.
Convert this Subtitle to another format.
This method leverages subby's advanced subtitle processing capabilities
including better WebVTT handling, SDH stripping, and common issue fixing.
Backend selection is data-driven (see ``tracks/subtitle_convert.py``): the best
available backend that supports source->target is used, falling back through the
capability chain on failure. The backend can be pinned via the ``conversion_method``
config key (``auto`` | ``subby`` | ``pysubs2`` | ``subtitleedit`` | ``pycaption``),
or nudged per-service via ``preferred_conversion_method``; an explicit config value
always wins.
``forced`` marks an explicit user request (``--sub-format``). Lossy downconverts of
styled formats (SSA/ASS -> SRT) are skipped unless ``forced`` is True.
"""
from unshackle.core.tracks.subtitle_convert import run_conversion
if not self.path or not self.path.exists():
raise ValueError("You must download the subtitle track first.")
if self.codec == codec:
return self.path
method = (
config.subtitle.get("conversion_method") or getattr(self, "preferred_conversion_method", None) or "auto"
)
pin = None if method == "auto" else method
return run_conversion(self, codec, pin=pin, forced=forced)
output_path = self.path.with_suffix(f".{codec.value.lower()}")
original_path = self.path
try:
# Convert to SRT using subby first
srt_subtitles = None
if self.codec == Subtitle.Codec.WebVTT:
converter = WebVTTConverter()
srt_subtitles = converter.from_file(self.path)
if self.codec == Subtitle.Codec.fVTT:
converter = WVTTConverter()
srt_subtitles = converter.from_file(self.path)
elif self.codec == Subtitle.Codec.SAMI:
converter = SAMIConverter()
srt_subtitles = converter.from_file(self.path)
if srt_subtitles is not None:
# Apply common fixes
fixer = CommonIssuesFixer()
fixed_srt, _ = fixer.from_srt(srt_subtitles)
# If target is SRT, we're done
if codec == Subtitle.Codec.SubRip:
fixed_srt.save(output_path, encoding="utf8")
else:
# Convert from SRT to target format using existing pycaption logic
temp_srt_path = self.path.with_suffix(".temp.srt")
fixed_srt.save(temp_srt_path, encoding="utf8")
# Parse the SRT and convert to target format
caption_set = self.parse(temp_srt_path.read_bytes(), Subtitle.Codec.SubRip)
self.merge_same_cues(caption_set)
writer = {
Subtitle.Codec.TimedTextMarkupLang: pycaption.DFXPWriter,
Subtitle.Codec.WebVTT: pycaption.WebVTTWriter,
}.get(codec)
if writer:
subtitle_text = writer().write(caption_set)
output_path.write_text(subtitle_text, encoding="utf8")
else:
# Fall back to existing conversion method
temp_srt_path.unlink()
return self._convert_standard(codec)
temp_srt_path.unlink()
if original_path.exists() and original_path != output_path:
original_path.unlink()
self.path = output_path
self.codec = codec
if callable(self.OnConverted):
self.OnConverted(codec)
return output_path
else:
# Fall back to existing conversion method
return self._convert_standard(codec)
except Exception:
# Fall back to existing conversion method on any error
return self._convert_standard(codec)
def convert_with_pysubs2(self, codec: Subtitle.Codec) -> Path:
@staticmethod
def extract_fonts(text: str) -> set[str]:
"""
Convert subtitle using pysubs2 library for broad format support.
Font names referenced by an ASS/SSA subtitle.
pysubs2 is a pure-Python library supporting SubRip (SRT), SubStation Alpha
(SSA/ASS), WebVTT, TTML, SAMI, MicroDVD, MPL2, and TMP formats.
Covers both sources that need attaching for correct rendering:
- the ``Fontname`` column of every ``Style:`` line in ``[V4+ Styles]``/``[V4 Styles]``
(column located from the section's ``Format:`` line, not assumed by index), and
- inline ``\\fn`` font overrides inside ``Dialogue`` override blocks.
Leading ``@`` (vertical-writing prefix) is stripped and names are de-duplicated
case-insensitively, preferring a mixed-case spelling over an all-lowercase one.
"""
if not self.path or not self.path.exists():
raise ValueError("You must download the subtitle track first.")
names: set[str] = set()
name_index = 1 # ASS default Style order: Name, Fontname, ...
in_styles = False
for line in text.splitlines():
stripped = line.strip()
if stripped.startswith("["):
in_styles = stripped.lower() in ("[v4+ styles]", "[v4 styles]")
continue
if not in_styles:
continue
if stripped.lower().startswith("format:"):
columns = [c.strip().lower() for c in stripped.split(":", 1)[1].split(",")]
if "fontname" in columns:
name_index = columns.index("fontname")
elif stripped.lower().startswith("style:"):
fields = stripped.split(":", 1)[1].split(",")
if len(fields) > name_index:
names.add(fields[name_index].strip())
if self.codec == codec:
return self.path
names.update(match.strip() for match in re.findall(r"\\fn([^\\}]+)", text))
output_path = self.path.with_suffix(f".{codec.value.lower()}")
original_path = self.path
codec_to_pysubs2_format = {
Subtitle.Codec.SubRip: "srt",
Subtitle.Codec.SubStationAlpha: "ssa",
Subtitle.Codec.SubStationAlphav4: "ass",
Subtitle.Codec.WebVTT: "vtt",
Subtitle.Codec.TimedTextMarkupLang: "ttml",
Subtitle.Codec.SAMI: "sami",
Subtitle.Codec.MicroDVD: "microdvd",
Subtitle.Codec.MPL2: "mpl2",
Subtitle.Codec.TMP: "tmp",
}
pysubs2_output_format = codec_to_pysubs2_format.get(codec)
if pysubs2_output_format is None:
return self._convert_standard(codec)
try:
subs = pysubs2.load(str(self.path), encoding="utf-8")
subs.save(str(output_path), format_=pysubs2_output_format, encoding="utf-8")
if original_path.exists() and original_path != output_path:
original_path.unlink()
self.path = output_path
self.codec = codec
if callable(self.OnConverted):
self.OnConverted(codec)
return output_path
except Exception:
return self._convert_standard(codec)
def convert(self, codec: Subtitle.Codec) -> Path:
"""
Convert this Subtitle to another Format.
The conversion method is determined by the 'conversion_method' setting in config:
- 'auto' (default): Uses subby for WebVTT/fVTT/SAMI; for SSA/ASS/MicroDVD/MPL2/TMP
uses SubtitleEdit if available, otherwise pysubs2; standard for others
- 'subby': Always uses subby with CommonIssuesFixer
- 'subtitleedit': Uses SubtitleEdit when available, falls back to pycaption
- 'pycaption': Uses only pycaption library
- 'pysubs2': Uses pysubs2 library
"""
# Check configuration for conversion method
conversion_method = config.subtitle.get("conversion_method", "auto")
if conversion_method == "subby":
return self.convert_with_subby(codec)
elif conversion_method == "subtitleedit":
return self._convert_standard(codec)
elif conversion_method == "pycaption":
return self._convert_pycaption_only(codec)
elif conversion_method == "pysubs2":
return self.convert_with_pysubs2(codec)
elif conversion_method == "auto":
if self.codec in (Subtitle.Codec.WebVTT, Subtitle.Codec.fVTT, Subtitle.Codec.SAMI):
return self.convert_with_subby(codec)
elif self.codec in (
Subtitle.Codec.SubStationAlpha,
Subtitle.Codec.SubStationAlphav4,
Subtitle.Codec.MicroDVD,
Subtitle.Codec.MPL2,
Subtitle.Codec.TMP,
):
if binaries.SubtitleEdit:
return self._convert_standard(codec)
else:
return self.convert_with_pysubs2(codec)
else:
return self._convert_standard(codec)
else:
return self._convert_standard(codec)
def _convert_pycaption_only(self, codec: Subtitle.Codec) -> Path:
"""
Convert subtitle using only pycaption library (no SubtitleEdit, no subby).
This is the original conversion method that only uses pycaption.
"""
if not self.path or not self.path.exists():
raise ValueError("You must download the subtitle track first.")
if self.codec == codec:
return self.path
output_path = self.path.with_suffix(f".{codec.value.lower()}")
original_path = self.path
# Use only pycaption for conversion
writer = {
Subtitle.Codec.SubRip: pycaption.SRTWriter,
Subtitle.Codec.TimedTextMarkupLang: pycaption.DFXPWriter,
Subtitle.Codec.WebVTT: pycaption.WebVTTWriter,
}.get(codec)
if writer is None:
raise NotImplementedError(f"Cannot convert {self.codec.name} to {codec.name} using pycaption only.")
caption_set = self.parse(self.path.read_bytes(), self.codec)
Subtitle.merge_same_cues(caption_set)
if codec == Subtitle.Codec.WebVTT:
Subtitle.filter_unwanted_cues(caption_set)
subtitle_text = writer().write(caption_set)
output_path.write_text(subtitle_text, encoding="utf8")
if original_path.exists() and original_path != output_path:
original_path.unlink()
self.path = output_path
self.codec = codec
if callable(self.OnConverted):
self.OnConverted(codec)
return output_path
def _convert_standard(self, codec: Subtitle.Codec) -> Path:
"""
Convert this Subtitle to another Format.
The file path location of the Subtitle data will be kept at the same
location but the file extension will be changed appropriately.
Supported formats:
- SubRip - SubtitleEdit or pycaption.SRTWriter
- TimedTextMarkupLang - SubtitleEdit or pycaption.DFXPWriter
- WebVTT - SubtitleEdit or pycaption.WebVTTWriter
- SubStationAlphav4 - SubtitleEdit
- SAMI - subby.SAMIConverter (when available)
- fTTML* - custom code using some pycaption functions
- fVTT* - custom code using some pycaption functions
*: Can read from format, but cannot convert to format
Note: It currently prioritizes using SubtitleEdit over PyCaption as
I have personally noticed more oddities with PyCaption parsing over
SubtitleEdit. Especially when working with TTML/DFXP where it would
often have timecodes and stuff mixed in/duplicated.
Returns the new file path of the Subtitle.
"""
if not self.path or not self.path.exists():
raise ValueError("You must download the subtitle track first.")
if self.codec == codec:
return self.path
output_path = self.path.with_suffix(f".{codec.value.lower()}")
original_path = self.path
if binaries.SubtitleEdit and self.codec not in (Subtitle.Codec.fTTML, Subtitle.Codec.fVTT):
sub_edit_format = {
Subtitle.Codec.SubRip: "subrip",
Subtitle.Codec.SubStationAlpha: "substationalpha",
Subtitle.Codec.SubStationAlphav4: "advancedsubstationalpha",
Subtitle.Codec.TimedTextMarkupLang: "timedtext1.0",
Subtitle.Codec.WebVTT: "webvtt",
Subtitle.Codec.SAMI: "sami",
Subtitle.Codec.MicroDVD: "microdvd",
}.get(codec, codec.name.lower())
sub_edit_args = [
str(binaries.SubtitleEdit),
"/convert",
str(self.path),
sub_edit_format,
f"/outputfilename:{output_path.name}",
"/encoding:utf8",
]
if codec == Subtitle.Codec.SubRip:
sub_edit_args.append("/ConvertColorsToDialog")
subprocess.run(sub_edit_args, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
else:
writer = {
# pycaption generally only supports these subtitle formats
Subtitle.Codec.SubRip: pycaption.SRTWriter,
Subtitle.Codec.TimedTextMarkupLang: pycaption.DFXPWriter,
Subtitle.Codec.WebVTT: pycaption.WebVTTWriter,
}.get(codec)
if writer is None:
raise NotImplementedError(f"Cannot yet convert {self.codec.name} to {codec.name}.")
caption_set = self.parse(self.path.read_bytes(), self.codec)
Subtitle.merge_same_cues(caption_set)
if codec == Subtitle.Codec.WebVTT:
Subtitle.filter_unwanted_cues(caption_set)
subtitle_text = writer().write(caption_set)
output_path.write_text(subtitle_text, encoding="utf8")
if original_path.exists() and original_path != output_path:
original_path.unlink()
self.path = output_path
self.codec = codec
if callable(self.OnConverted):
self.OnConverted(codec)
return output_path
canonical: dict[str, str] = {}
for name in (raw.lstrip("@").strip() for raw in names):
if not name:
continue
key = name.lower()
if key not in canonical or (name != name.lower() and canonical[key] == canonical[key].lower()):
canonical[key] = name
return set(canonical.values())
@staticmethod
def parse(data: bytes, codec: Subtitle.Codec) -> pycaption.CaptionSet:
@@ -1267,25 +1033,13 @@ class Subtitle(Track):
)
if binaries.SubtitleEdit and use_subtitleedit:
output_format = {
Subtitle.Codec.SubRip: "subrip",
Subtitle.Codec.SubStationAlpha: "substationalpha",
Subtitle.Codec.SubStationAlphav4: "advancedsubstationalpha",
Subtitle.Codec.TimedTextMarkupLang: "timedtext1.0",
Subtitle.Codec.WebVTT: "webvtt",
Subtitle.Codec.SAMI: "sami",
Subtitle.Codec.MicroDVD: "microdvd",
}.get(self.codec, self.codec.name.lower())
from unshackle.core.tracks.subtitle_convert import SUBTITLE_EDIT_FORMATS, subtitleedit_args
output_format = SUBTITLE_EDIT_FORMATS.get(self.codec, self.codec.name.lower())
subprocess.run(
[
str(binaries.SubtitleEdit),
"/convert",
str(self.path),
output_format,
"/encoding:utf8",
"/overwrite",
"/RemoveTextForHI",
],
subtitleedit_args(
binaries.SubtitleEdit, self.path, output_format, output_folder=self.path.parent, remove_hi=True
),
check=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
@@ -1330,26 +1084,14 @@ class Subtitle(Track):
if not binaries.SubtitleEdit:
raise EnvironmentError("SubtitleEdit executable not found...")
output_format = {
Subtitle.Codec.SubRip: "subrip",
Subtitle.Codec.SubStationAlpha: "substationalpha",
Subtitle.Codec.SubStationAlphav4: "advancedsubstationalpha",
Subtitle.Codec.TimedTextMarkupLang: "timedtext1.0",
Subtitle.Codec.WebVTT: "webvtt",
Subtitle.Codec.SAMI: "sami",
Subtitle.Codec.MicroDVD: "microdvd",
}.get(self.codec, self.codec.name.lower())
from unshackle.core.tracks.subtitle_convert import SUBTITLE_EDIT_FORMATS, subtitleedit_args
output_format = SUBTITLE_EDIT_FORMATS.get(self.codec, self.codec.name.lower())
subprocess.run(
[
str(binaries.SubtitleEdit),
"/convert",
str(self.path),
output_format,
"/ReverseRtlStartEnd",
"/encoding:utf8",
"/overwrite",
],
subtitleedit_args(
binaries.SubtitleEdit, self.path, output_format, output_folder=self.path.parent, reverse_rtl=True
),
check=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
+313
View File
@@ -0,0 +1,313 @@
"""
Subtitle conversion backend registry.
Routing is data-driven: each backend declares which (source -> target) codec pairs it can
read/write, whether it is available in the current environment, and a preference rank.
``resolve_backends`` filters the registry to the available backends that support the
requested pair and orders them by rank; ``run_conversion`` tries each in turn (a real
fallback chain) until one succeeds.
The public entry point stays ``Subtitle.convert`` / ``Subtitle.strip_hearing_impaired`` in
subtitle.py — this module only holds the selection + conversion logic so subtitle.py keeps
the codec enum, ``parse``, sanitizers and cue helpers (the collaborators backends reuse).
"""
from __future__ import annotations
import logging
import subprocess
from pathlib import Path
from typing import Optional, Protocol
import pycaption
import pysubs2
from subby import CommonIssuesFixer, SAMIConverter, WebVTTConverter, WVTTConverter
from unshackle.core import binaries
from unshackle.core.tracks.subtitle import Subtitle
log = logging.getLogger("subtitle")
Codec = Subtitle.Codec
# SubtitleEdit (and the cross-platform seconv port) /convert format names.
# Shared by SubtitleEditBackend, strip_hearing_impaired and reverse_rtl so the map lives once.
SUBTITLE_EDIT_FORMATS: dict[Codec, str] = {
Codec.SubRip: "subrip",
Codec.SubStationAlpha: "substationalpha",
Codec.SubStationAlphav4: "advancedsubstationalpha",
Codec.TimedTextMarkupLang: "timedtext1.0",
Codec.WebVTT: "webvtt",
Codec.SAMI: "sami",
Codec.MicroDVD: "microdvd",
}
# pycaption can only WRITE these three formats.
PYCAPTION_WRITERS = {
Codec.SubRip: pycaption.SRTWriter,
Codec.TimedTextMarkupLang: pycaption.DFXPWriter,
Codec.WebVTT: pycaption.WebVTTWriter,
}
# pysubs2 format identifiers per codec.
PYSUBS2_FORMATS: dict[Codec, str] = {
Codec.SubRip: "srt",
Codec.SubStationAlpha: "ssa",
Codec.SubStationAlphav4: "ass",
Codec.WebVTT: "vtt",
Codec.TimedTextMarkupLang: "ttml",
Codec.SAMI: "sami",
Codec.MicroDVD: "microdvd",
Codec.MPL2: "mpl2",
Codec.TMP: "tmp",
}
def subtitleedit_args(
binary: object,
src: Path,
fmt: str,
*,
output_folder: Optional[Path] = None,
convert_colors: bool = False,
remove_hi: bool = False,
reverse_rtl: bool = False,
) -> list[str]:
"""
Build a SubtitleEdit batch-convert command.
Targets the SubtitleEdit 5+ CLI (``SeConv`` / ``seconv`` on every platform), which takes
``--flags`` with a positional ``<pattern> <format>`` (no legacy ``/convert`` verb). The
SE5 converter names the output ``<input-stem>.<format-ext>``; pass ``output_folder`` to
place it next to a chosen path (a bare ``--output-filename`` resolves against the *cwd*,
not the input dir, so we always steer with ``--output-folder``). ``--overwrite`` is always
set so re-runs and in-place transforms (SDH/RTL) don't fail on an existing file.
"""
args = [str(binary), str(src), fmt, "--encoding:utf-8", "--overwrite"]
if output_folder is not None:
args.append(f"--output-folder:{output_folder}")
if convert_colors:
args.append("--convert-colors-to-dialog")
if remove_hi:
args.append("--remove-text-for-hi")
if reverse_rtl:
args.append("--reverse-rtl-start-end")
return args
# Styled SubStation formats flattened to SRT lose positioning/colours/italics.
# Never performed automatically — only when the user explicitly forces a target format.
LOSSY_DOWNCONVERTS: frozenset[tuple[Codec, Codec]] = frozenset(
{
(Codec.SubStationAlpha, Codec.SubRip),
(Codec.SubStationAlphav4, Codec.SubRip),
}
)
class SubtitleBackend(Protocol):
name: str
def is_available(self) -> bool: ...
def can_convert(self, source: Codec, target: Codec) -> bool: ...
def rank(self, source: Codec, target: Codec) -> int: ...
def convert(self, source: Codec, src: Path, target: Codec, out: Path) -> None:
"""Convert ``src`` (a ``source`` file) to ``target``, writing to ``out``. Raise on failure."""
...
class SubtitleEditBackend:
"""SubtitleEdit / seconv CLI. Highest fidelity (keeps positioning + italics) when present."""
name = "subtitleedit"
reads = frozenset(SUBTITLE_EDIT_FORMATS)
writes = frozenset(SUBTITLE_EDIT_FORMATS)
def is_available(self) -> bool:
return bool(binaries.SubtitleEdit)
def can_convert(self, source: Codec, target: Codec) -> bool:
# Segmented box formats cannot be read by SubtitleEdit.
if source in (Codec.fTTML, Codec.fVTT):
return False
return source in self.reads and target in self.writes
def rank(self, source: Codec, target: Codec) -> int:
return 0
def convert(self, source: Codec, src: Path, target: Codec, out: Path) -> None:
args = subtitleedit_args(
binaries.SubtitleEdit,
src,
SUBTITLE_EDIT_FORMATS[target],
output_folder=out.parent,
convert_colors=(target == Codec.SubRip),
)
subprocess.run(args, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
# SE5 names the output <input-stem>.<format-ext>, which may differ from our target
# suffix (e.g. timedtext1.0 -> .ttml). Normalise it onto `out`.
if not out.exists():
produced = next((p for p in src.parent.glob(f"{src.stem}.*") if p not in (src, out)), None)
if produced is None:
raise FileNotFoundError(f"SubtitleEdit produced no output for {src.name} -> {target.name}")
produced.replace(out)
class Pysubs2Backend:
"""pysubs2 — pure Python, broad format support, best fidelity for SSA/ASS (native style model)."""
name = "pysubs2"
formats = frozenset(PYSUBS2_FORMATS)
def is_available(self) -> bool:
return True
def can_convert(self, source: Codec, target: Codec) -> bool:
return source in self.formats and target in self.formats
def rank(self, source: Codec, target: Codec) -> int:
# Preferred reader for styled SubStation sources; solid general fallback otherwise.
return 1 if source in (Codec.SubStationAlpha, Codec.SubStationAlphav4) else 2
def convert(self, source: Codec, src: Path, target: Codec, out: Path) -> None:
subs = pysubs2.load(str(src), encoding="utf-8")
subs.save(str(out), format_=PYSUBS2_FORMATS[target], encoding="utf-8")
class SubbyBackend:
"""subby — purpose-built for streaming subs. WebVTT/fVTT/SAMI -> SRT + CommonIssuesFixer cleanup."""
name = "subby"
reads = frozenset({Codec.WebVTT, Codec.fVTT, Codec.SAMI})
# Native SRT output; non-SRT targets re-encoded from the SRT intermediate via pycaption.
writes = frozenset({Codec.SubRip, Codec.TimedTextMarkupLang, Codec.WebVTT})
converters = {
Codec.WebVTT: WebVTTConverter,
Codec.fVTT: WVTTConverter,
Codec.SAMI: SAMIConverter,
}
def is_available(self) -> bool:
return True
def can_convert(self, source: Codec, target: Codec) -> bool:
return source in self.reads and target in self.writes
def rank(self, source: Codec, target: Codec) -> int:
# Great for *->SRT (adds cleanup); the SRT intermediate is lossy for other targets.
return 1 if target == Codec.SubRip else 5
def convert(self, source: Codec, src: Path, target: Codec, out: Path) -> None:
srt_subtitles = self.converters[source]().from_file(src)
fixed_srt, _ = CommonIssuesFixer().from_srt(srt_subtitles)
if target == Codec.SubRip:
fixed_srt.save(out, encoding="utf8")
return
temp_srt = src.with_suffix(".temp.srt")
fixed_srt.save(temp_srt, encoding="utf8")
try:
caption_set = Subtitle.parse(temp_srt.read_bytes(), Codec.SubRip)
Subtitle.merge_same_cues(caption_set)
out.write_text(PYCAPTION_WRITERS[target]().write(caption_set), encoding="utf8")
finally:
temp_srt.unlink(missing_ok=True)
class PycaptionBackend:
"""pycaption — last resort. Note: flattens positioning/italics (devine #39), so ranked last."""
name = "pycaption"
reads = frozenset({Codec.SubRip, Codec.TimedTextMarkupLang, Codec.WebVTT, Codec.SAMI, Codec.fTTML, Codec.fVTT})
writes = frozenset(PYCAPTION_WRITERS)
def is_available(self) -> bool:
return True
def can_convert(self, source: Codec, target: Codec) -> bool:
return source in self.reads and target in self.writes
def rank(self, source: Codec, target: Codec) -> int:
return 9
def convert(self, source: Codec, src: Path, target: Codec, out: Path) -> None:
caption_set = Subtitle.parse(src.read_bytes(), source)
Subtitle.merge_same_cues(caption_set)
if target == Codec.WebVTT:
Subtitle.filter_unwanted_cues(caption_set)
out.write_text(PYCAPTION_WRITERS[target]().write(caption_set), encoding="utf8")
REGISTRY: list[SubtitleBackend] = [
SubtitleEditBackend(),
SubbyBackend(),
Pysubs2Backend(),
PycaptionBackend(),
]
def resolve_backends(source: Codec, target: Codec, *, pin: Optional[str] = None) -> list[SubtitleBackend]:
"""Available backends that support source->target, ordered by rank. A pin is tried first."""
available = [b for b in REGISTRY if b.is_available() and b.can_convert(source, target)]
if pin:
pinned = [b for b in available if b.name == pin]
rest = sorted((b for b in available if b.name != pin), key=lambda b: b.rank(source, target))
return pinned + rest
return sorted(available, key=lambda b: b.rank(source, target))
def finalize(sub: Subtitle, target: Codec, out: Path) -> Path:
"""Swap the track onto the converted file and fire the OnConverted callback."""
original = sub.path
if original and original.exists() and original != out:
original.unlink()
sub.path = out
sub.codec = target
if callable(sub.OnConverted):
sub.OnConverted(target)
return out
def run_conversion(sub: Subtitle, target: Codec, *, pin: Optional[str] = None, forced: bool = False) -> Path:
"""
Convert ``sub`` to ``target`` using the best available backend, falling back through the
capability chain on failure.
``forced`` is True only for explicit user requests (``--sub-format``); lossy downconverts
(styled SubStation -> SRT) are skipped unless forced.
"""
if sub.path is None or not sub.path.exists():
raise ValueError("You must download the subtitle track first.")
if sub.codec is None:
raise ValueError("Subtitle has no codec to convert from.")
source, src = sub.codec, sub.path
if source == target:
return src
if (source, target) in LOSSY_DOWNCONVERTS and not forced:
log.info(
f"Keeping {source.name} subtitle as-is "
f"(skipping lossy auto-conversion to {target.name}; pass --sub-format to force)"
)
return src
chain = resolve_backends(source, target, pin=pin)
if not chain:
raise NotImplementedError(f"Cannot convert {source.name} to {target.name}.")
out = src.with_suffix(f".{target.value.lower()}")
last_exc: Optional[Exception] = None
for backend in chain:
try:
backend.convert(source, src, target, out)
except Exception as e:
last_exc = e
log.debug(f"Subtitle backend {backend.name} failed ({source.name}->{target.name}): {e}")
continue
log.debug(f"Converted subtitle {source.name}->{target.name} via {backend.name}")
return finalize(sub, target, out)
raise RuntimeError(f"All subtitle backends failed for {source.name}->{target.name}") from last_exc
+26
View File
@@ -339,6 +339,32 @@ class Tracks:
merged.append(video)
return merged
@staticmethod
def partition_hybrid_videos(
videos: list[Video], non_hybrid_ranges: list[Video.Range]
) -> tuple[list[Video], list[Video]]:
"""Split videos into hybrid-ingredient candidates and the standalone-deliverable pool.
HDR10/HDR10+/DV tracks are hybrid ingredients; they only enter the standalone
pool when their range was explicitly requested alongside HYBRID, so e.g.
`-r HYBRID` muxes only the hybrid while `-r HYBRID,HDR10P` also delivers HDR10+.
"""
ingredient_ranges = (Video.Range.HDR10, Video.Range.HDR10P, Video.Range.DV)
hybrid_candidates = [v for v in videos if v.range in ingredient_ranges]
non_hybrid = [v for v in videos if v.range not in ingredient_ranges or v.range in non_hybrid_ranges]
return hybrid_candidates, non_hybrid
@staticmethod
def flag_hybrid_ingredients(hybrid_selected: list[Video], non_hybrid_selected: list[Video]) -> None:
"""Mark tracks selected only as hybrid ingredients so the standalone mux loop skips them.
A track that was also picked as an explicit deliverable (same track in both
selections) stays unflagged and is muxed standalone alongside the hybrid.
"""
for video in hybrid_selected:
if video not in non_hybrid_selected:
video.hybrid_base_only = True
def select_hybrid(self, tracks, quality, worst: bool = False):
# Prefer HDR10+ over HDR10 as the base layer (preserves dynamic metadata)
base_ranges = (Video.Range.HDR10P, Video.Range.HDR10)
+4 -2
View File
@@ -726,8 +726,10 @@ class FPS(ast.NodeVisitor):
return self.visit(node.left) / self.visit(node.right)
raise ValueError(f"Invalid operation: {node.op}")
def visit_Num(self, node: ast.Num) -> complex:
return node.n
def visit_Constant(self, node: ast.Constant) -> float:
if not isinstance(node.value, (int, float)):
raise ValueError(f"Invalid fps value: {node.value!r}")
return node.value
def visit_Expr(self, node: ast.Expr) -> float:
return self.visit(node.value)
+5
View File
@@ -131,6 +131,8 @@ class SubtitleCodecChoice(click.Choice):
if value_lower not in choices:
choices.append(value_lower)
choices.append("original")
self.aliases = aliases
super().__init__(choices, case_sensitive=False)
@@ -138,6 +140,9 @@ class SubtitleCodecChoice(click.Choice):
if not value:
return None
if str(value).lower() == "original":
return "original"
# First try to convert using the parent class
converted_value = super().convert(value, param, ctx)
+3
View File
@@ -75,6 +75,9 @@ class EXAMPLE(Service):
TITLE_RE = r"^(?:https?://(?:www\.)?domain\.com/details/)?(?P<title_id>[^/?#]+)"
# NO_SUBTITLES: service-level idiom telling the pipeline subs are handled in-band.
NO_SUBTITLES = False
# VAULT_TAG: store/read keys under a different vault namespace than this service's tag.
# Lets sibling services share one key vault. Omit to use the service's own tag.
VAULT_TAG = "DIFFERENT_NAME"
# Map our API's range strings <-> unshackle's Video.Range enum.
VIDEO_RANGE_MAP = {
+35 -13
View File
@@ -448,30 +448,41 @@ filenames:
# - pysubs2: Use pysubs2 library (supports SRT/SSA/ASS/WebVTT/TTML/SAMI/MicroDVD/MPL2/TMP)
subtitle:
conversion_method: auto
# sdh_method: Method to use for SDH (hearing impaired) stripping
# Which backend converts subtitles (data-driven registry, pin-then-fallback)
# - auto (default): best available by rank (SubtitleEdit > subby/pysubs2 > pycaption)
# - subby | pysubs2 | subtitleedit | pycaption: pin that backend first, still falls back
# Styled ASS/SSA are never auto-downconverted to SRT (kept as-is); --sub-format srt overrides.
# SubtitleEdit on Linux/macOS = install the SE5 "SeConv" (seconv) CLI on PATH or unshackle/binaries/.
sdh_method: auto
# Method to use for SDH (hearing impaired) stripping
# - auto (default): Try subby (SRT only), then SubtitleEdit (if available), then subtitle-filter
# - subby: Use subby library (SRT only)
# - subtitleedit: Use SubtitleEdit tool (Windows only, falls back to subtitle-filter)
# - subtitleedit: Use SubtitleEdit / seconv (SE5 CLI, cross-platform), falls back to subtitle-filter
# - filter-subs: Use subtitle-filter library directly
sdh_method: auto
# strip_sdh: Automatically create stripped (non-SDH) versions of SDH subtitles
# Set to false to disable automatic SDH stripping entirely (default: true)
strip_sdh: true
# convert_before_strip: Auto-convert VTT/other formats to SRT before using subtitle-filter
# This ensures compatibility when subtitle-filter is used as fallback (default: true)
# Automatically create stripped (non-SDH) versions of SDH subtitles
# Set to false to disable automatic SDH stripping entirely (default: true)
convert_before_strip: true
# preserve_formatting: Preserve original subtitle formatting (tags, positioning, styling)
# Auto-convert VTT/other formats to SRT before using subtitle-filter
# This ensures compatibility when subtitle-filter is used as fallback (default: true)
preserve_formatting: true
# Preserve original subtitle formatting (tags, positioning, styling)
# When true, skips pycaption processing for WebVTT files to keep tags like <i>, <b>, positioning intact
# Combined with no sub_format setting, ensures subtitles remain in their original format (default: true)
preserve_formatting: true
# output_mode: Output mode for subtitles
output_mode: mux
# Output mode for subtitles
# - mux: Embed subtitles in MKV container only (default)
# - sidecar: Save subtitles as separate files only
# - both: Embed in MKV AND save as sidecar files
output_mode: mux
# sidecar_format: Format for sidecar subtitle files
# Options: srt, vtt, ass, original (keep current format)
sidecar_format: srt
# Format for sidecar subtitle files
# Options: srt, vtt, ass, original (keep current format)
# Configuration for pywidevine and pyplayready's serve functionality
# Also used for remote services (unshackle serve)
@@ -514,6 +525,17 @@ serve:
# playready_devices: # PlayReady device paths (auto-populated from directories.prds)
# - '/path/to/device.prd'
# Per-request override gates (both default OFF = locked to server-side config).
# A /api/download job may ask to use a specific server-side CDM device or to
# authenticate with client-supplied credentials; both are rejected with 403 unless
# explicitly opted in here, so a default deployment can't be driven to use arbitrary
# devices or inject credentials.
# cdm_overrides: true # true = allow any device; or a list of permitted device names:
# cdm_overrides:
# - generic_nexus_4464_l3
# allow_job_credentials: true # allow a per-request `credential` / `credentials` in a job
# # (each distinct credential gets an isolated token cache)
# Optional: any /api/download flag can be set here as a server-side default.
# Per-request body values still win. Useful for raising concurrency without
# changing every client call. Full list of accepted keys: see docs/API.md.
Generated
+58 -54
View File
@@ -13,7 +13,7 @@ wheels = [
[[package]]
name = "aiohttp"
version = "3.13.5"
version = "3.14.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "aiohappyeyeballs" },
@@ -23,61 +23,65 @@ dependencies = [
{ name = "frozenlist" },
{ name = "multidict" },
{ name = "propcache" },
{ name = "typing-extensions" },
{ name = "yarl" },
]
sdist = { url = "https://files.pythonhosted.org/packages/77/9a/152096d4808df8e4268befa55fba462f440f14beab85e8ad9bf990516918/aiohttp-3.13.5.tar.gz", hash = "sha256:9d98cc980ecc96be6eb4c1994ce35d28d8b1f5e5208a23b421187d1209dbb7d1", size = 7858271, upload-time = "2026-03-31T22:01:03.343Z" }
sdist = { url = "https://files.pythonhosted.org/packages/ee/ab/93ce242f899b68c51b0578c027aafa791ab3614cb9345fa5d37b5f5c8e3e/aiohttp-3.14.0.tar.gz", hash = "sha256:2882de819734c715fd1b9c11c97e09fa020d14438203d1d354d8ed1702791c9b", size = 7940674, upload-time = "2026-06-01T19:41:02.763Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/bd/85/cebc47ee74d8b408749073a1a46c6fcba13d170dc8af7e61996c6c9394ac/aiohttp-3.13.5-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:02222e7e233295f40e011c1b00e3b0bd451f22cf853a0304c3595633ee47da4b", size = 750547, upload-time = "2026-03-31T21:56:30.024Z" },
{ url = "https://files.pythonhosted.org/packages/05/98/afd308e35b9d3d8c9ec54c0918f1d722c86dc17ddfec272fcdbcce5a3124/aiohttp-3.13.5-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:bace460460ed20614fa6bc8cb09966c0b8517b8c58ad8046828c6078d25333b5", size = 503535, upload-time = "2026-03-31T21:56:31.935Z" },
{ url = "https://files.pythonhosted.org/packages/6f/4d/926c183e06b09d5270a309eb50fbde7b09782bfd305dec1e800f329834fb/aiohttp-3.13.5-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:8f546a4dc1e6a5edbb9fd1fd6ad18134550e096a5a43f4ad74acfbd834fc6670", size = 497830, upload-time = "2026-03-31T21:56:33.654Z" },
{ url = "https://files.pythonhosted.org/packages/e4/d6/f47d1c690f115a5c2a5e8938cce4a232a5be9aac5c5fb2647efcbbbda333/aiohttp-3.13.5-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c86969d012e51b8e415a8c6ce96f7857d6a87d6207303ab02d5d11ef0cad2274", size = 1682474, upload-time = "2026-03-31T21:56:35.513Z" },
{ url = "https://files.pythonhosted.org/packages/01/44/056fd37b1bb52eac760303e5196acc74d9d546631b035704ae5927f7b4ac/aiohttp-3.13.5-cp310-cp310-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:b6f6cd1560c5fa427e3b6074bb24d2c64e225afbb7165008903bd42e4e33e28a", size = 1655259, upload-time = "2026-03-31T21:56:37.843Z" },
{ url = "https://files.pythonhosted.org/packages/91/9f/78eb1a20c1c28ae02f6a3c0f4d7b0dcc66abce5290cadd53d78ce3084175/aiohttp-3.13.5-cp310-cp310-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:636bc362f0c5bbc7372bc3ae49737f9e3030dbce469f0f422c8f38079780363d", size = 1736204, upload-time = "2026-03-31T21:56:39.822Z" },
{ url = "https://files.pythonhosted.org/packages/de/6c/d20d7de23f0b52b8c1d9e2033b2db1ac4dacbb470bb74c56de0f5f86bb4f/aiohttp-3.13.5-cp310-cp310-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:6a7cbeb06d1070f1d14895eeeed4dac5913b22d7b456f2eb969f11f4b3993796", size = 1826198, upload-time = "2026-03-31T21:56:41.378Z" },
{ url = "https://files.pythonhosted.org/packages/2f/86/a6f3ff1fd795f49545a7c74b2c92f62729135d73e7e4055bf74da5a26c82/aiohttp-3.13.5-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:bca9ef7517fd7874a1a08970ae88f497bf5c984610caa0bf40bd7e8450852b95", size = 1681329, upload-time = "2026-03-31T21:56:43.374Z" },
{ url = "https://files.pythonhosted.org/packages/fb/68/84cd3dab6b7b4f3e6fe9459a961acb142aaab846417f6e8905110d7027e5/aiohttp-3.13.5-cp310-cp310-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:019a67772e034a0e6b9b17c13d0a8fe56ad9fb150fc724b7f3ffd3724288d9e5", size = 1560023, upload-time = "2026-03-31T21:56:45.031Z" },
{ url = "https://files.pythonhosted.org/packages/41/2c/db61b64b0249e30f954a65ab4cb4970ced57544b1de2e3c98ee5dc24165f/aiohttp-3.13.5-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:f34ecee82858e41dd217734f0c41a532bd066bcaab636ad830f03a30b2a96f2a", size = 1652372, upload-time = "2026-03-31T21:56:47.075Z" },
{ url = "https://files.pythonhosted.org/packages/25/6f/e96988a6c982d047810c772e28c43c64c300c943b0ed5c1c0c4ce1e1027c/aiohttp-3.13.5-cp310-cp310-musllinux_1_2_armv7l.whl", hash = "sha256:4eac02d9af4813ee289cd63a361576da36dba57f5a1ab36377bc2600db0cbb73", size = 1662031, upload-time = "2026-03-31T21:56:48.835Z" },
{ url = "https://files.pythonhosted.org/packages/b7/26/a56feace81f3d347b4052403a9d03754a0ab23f7940780dada0849a38c92/aiohttp-3.13.5-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:4beac52e9fe46d6abf98b0176a88154b742e878fdf209d2248e99fcdf73cd297", size = 1708118, upload-time = "2026-03-31T21:56:50.833Z" },
{ url = "https://files.pythonhosted.org/packages/78/6e/b6173a8ff03d01d5e1a694bc06764b5dad1df2d4ed8f0ceec12bb3277936/aiohttp-3.13.5-cp310-cp310-musllinux_1_2_riscv64.whl", hash = "sha256:c180f480207a9b2475f2b8d8bd7204e47aec952d084b2a2be58a782ffcf96074", size = 1548667, upload-time = "2026-03-31T21:56:52.81Z" },
{ url = "https://files.pythonhosted.org/packages/16/13/13296ffe2c132d888b3fe2c195c8b9c0c24c89c3fa5cc2c44464dc23b22e/aiohttp-3.13.5-cp310-cp310-musllinux_1_2_s390x.whl", hash = "sha256:2837fb92951564d6339cedae4a7231692aa9f73cbc4fb2e04263b96844e03b4e", size = 1724490, upload-time = "2026-03-31T21:56:54.541Z" },
{ url = "https://files.pythonhosted.org/packages/7a/b4/1f1c287f4a79782ef36e5a6e62954c85343bc30470d862d30bd5f26c9fa2/aiohttp-3.13.5-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:d9010032a0b9710f58012a1e9c222528763d860ba2ee1422c03473eab47703e7", size = 1667109, upload-time = "2026-03-31T21:56:56.21Z" },
{ url = "https://files.pythonhosted.org/packages/ef/42/8461a2aaf60a8f4ea4549a4056be36b904b0eb03d97ca9a8a2604681a500/aiohttp-3.13.5-cp310-cp310-win32.whl", hash = "sha256:7c4b6668b2b2b9027f209ddf647f2a4407784b5d88b8be4efcc72036f365baf9", size = 439478, upload-time = "2026-03-31T21:56:58.292Z" },
{ url = "https://files.pythonhosted.org/packages/e5/71/06956304cb5ee439dfe8d86e1b2e70088bd88ed1ced1f42fb29e5d855f0e/aiohttp-3.13.5-cp310-cp310-win_amd64.whl", hash = "sha256:cd3db5927bf9167d5a6157ddb2f036f6b6b0ad001ac82355d43e97a4bde76d76", size = 462047, upload-time = "2026-03-31T21:57:00.257Z" },
{ url = "https://files.pythonhosted.org/packages/d6/f5/a20c4ac64aeaef1679e25c9983573618ff765d7aa829fa2b84ae7573169e/aiohttp-3.13.5-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:7ab7229b6f9b5c1ba4910d6c41a9eb11f543eadb3f384df1b4c293f4e73d44d6", size = 757513, upload-time = "2026-03-31T21:57:02.146Z" },
{ url = "https://files.pythonhosted.org/packages/75/0a/39fa6c6b179b53fcb3e4b3d2b6d6cad0180854eda17060c7218540102bef/aiohttp-3.13.5-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:8f14c50708bb156b3a3ca7230b3d820199d56a48e3af76fa21c2d6087190fe3d", size = 506748, upload-time = "2026-03-31T21:57:04.275Z" },
{ url = "https://files.pythonhosted.org/packages/87/ec/e38ce072e724fd7add6243613f8d1810da084f54175353d25ccf9f9c7e5a/aiohttp-3.13.5-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:e7d2f8616f0ff60bd332022279011776c3ac0faa0f1b463f7bb12326fbc97a1c", size = 501673, upload-time = "2026-03-31T21:57:06.208Z" },
{ url = "https://files.pythonhosted.org/packages/ba/ba/3bc7525d7e2beaa11b309a70d48b0d3cfc3c2089ec6a7d0820d59c657053/aiohttp-3.13.5-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a2567b72e1ffc3ab25510db43f355b29eeada56c0a622e58dcdb19530eb0a3cb", size = 1763757, upload-time = "2026-03-31T21:57:07.882Z" },
{ url = "https://files.pythonhosted.org/packages/5e/ab/e87744cf18f1bd78263aba24924d4953b41086bd3a31d22452378e9028a0/aiohttp-3.13.5-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:fb0540c854ac9c0c5ad495908fdfd3e332d553ec731698c0e29b1877ba0d2ec6", size = 1720152, upload-time = "2026-03-31T21:57:09.946Z" },
{ url = "https://files.pythonhosted.org/packages/6b/f3/ed17a6f2d742af17b50bae2d152315ed1b164b07a5fd5cc1754d99e4dfa5/aiohttp-3.13.5-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:c9883051c6972f58bfc4ebb2116345ee2aa151178e99c3f2b2bbe2af712abd13", size = 1818010, upload-time = "2026-03-31T21:57:12.157Z" },
{ url = "https://files.pythonhosted.org/packages/53/06/ecbc63dc937192e2a5cb46df4d3edb21deb8225535818802f210a6ea5816/aiohttp-3.13.5-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:2294172ce08a82fb7c7273485895de1fa1186cc8294cfeb6aef4af42ad261174", size = 1907251, upload-time = "2026-03-31T21:57:14.023Z" },
{ url = "https://files.pythonhosted.org/packages/7e/a5/0521aa32c1ddf3aa1e71dcc466be0b7db2771907a13f18cddaa45967d97b/aiohttp-3.13.5-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:3a807cabd5115fb55af198b98178997a5e0e57dead43eb74a93d9c07d6d4a7dc", size = 1759969, upload-time = "2026-03-31T21:57:16.146Z" },
{ url = "https://files.pythonhosted.org/packages/f6/78/a38f8c9105199dd3b9706745865a8a59d0041b6be0ca0cc4b2ccf1bab374/aiohttp-3.13.5-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:aa6d0d932e0f39c02b80744273cd5c388a2d9bc07760a03164f229c8e02662f6", size = 1616871, upload-time = "2026-03-31T21:57:17.856Z" },
{ url = "https://files.pythonhosted.org/packages/6f/41/27392a61ead8ab38072105c71aa44ff891e71653fe53d576a7067da2b4e8/aiohttp-3.13.5-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:60869c7ac4aaabe7110f26499f3e6e5696eae98144735b12a9c3d9eae2b51a49", size = 1739844, upload-time = "2026-03-31T21:57:19.679Z" },
{ url = "https://files.pythonhosted.org/packages/6e/55/5564e7ae26d94f3214250009a0b1c65a0c6af4bf88924ccb6fdab901de28/aiohttp-3.13.5-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:26d2f8546f1dfa75efa50c3488215a903c0168d253b75fba4210f57ab77a0fb8", size = 1731969, upload-time = "2026-03-31T21:57:22.006Z" },
{ url = "https://files.pythonhosted.org/packages/6d/c5/705a3929149865fc941bcbdd1047b238e4a72bcb215a9b16b9d7a2e8d992/aiohttp-3.13.5-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:f1162a1492032c82f14271e831c8f4b49f2b6078f4f5fc74de2c912fa225d51d", size = 1795193, upload-time = "2026-03-31T21:57:24.256Z" },
{ url = "https://files.pythonhosted.org/packages/a6/19/edabed62f718d02cff7231ca0db4ef1c72504235bc467f7b67adb1679f48/aiohttp-3.13.5-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:8b14eb3262fad0dc2f89c1a43b13727e709504972186ff6a99a3ecaa77102b6c", size = 1606477, upload-time = "2026-03-31T21:57:26.364Z" },
{ url = "https://files.pythonhosted.org/packages/de/fc/76f80ef008675637d88d0b21584596dc27410a990b0918cb1e5776545b5b/aiohttp-3.13.5-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:ca9ac61ac6db4eb6c2a0cd1d0f7e1357647b638ccc92f7e9d8d133e71ed3c6ac", size = 1813198, upload-time = "2026-03-31T21:57:28.316Z" },
{ url = "https://files.pythonhosted.org/packages/e5/67/5b3ac26b80adb20ea541c487f73730dc8fa107d632c998f25bbbab98fcda/aiohttp-3.13.5-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:7996023b2ed59489ae4762256c8516df9820f751cf2c5da8ed2fb20ee50abab3", size = 1752321, upload-time = "2026-03-31T21:57:30.549Z" },
{ url = "https://files.pythonhosted.org/packages/88/06/e4a2e49255ea23fa4feeb5ab092d90240d927c15e47b5b5c48dff5a9ce29/aiohttp-3.13.5-cp311-cp311-win32.whl", hash = "sha256:77dfa48c9f8013271011e51c00f8ada19851f013cde2c48fca1ba5e0caf5bb06", size = 439069, upload-time = "2026-03-31T21:57:32.388Z" },
{ url = "https://files.pythonhosted.org/packages/c0/43/8c7163a596dab4f8be12c190cf467a1e07e4734cf90eebb39f7f5d53fc6a/aiohttp-3.13.5-cp311-cp311-win_amd64.whl", hash = "sha256:d3a4834f221061624b8887090637db9ad4f61752001eae37d56c52fddade2dc8", size = 462859, upload-time = "2026-03-31T21:57:34.455Z" },
{ url = "https://files.pythonhosted.org/packages/be/6f/353954c29e7dcce7cf00280a02c75f30e133c00793c7a2ed3776d7b2f426/aiohttp-3.13.5-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:023ecba036ddd840b0b19bf195bfae970083fd7024ce1ac22e9bba90464620e9", size = 748876, upload-time = "2026-03-31T21:57:36.319Z" },
{ url = "https://files.pythonhosted.org/packages/f5/1b/428a7c64687b3b2e9cd293186695affc0e1e54a445d0361743b231f11066/aiohttp-3.13.5-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:15c933ad7920b7d9a20de151efcd05a6e38302cbf0e10c9b2acb9a42210a2416", size = 499557, upload-time = "2026-03-31T21:57:38.236Z" },
{ url = "https://files.pythonhosted.org/packages/29/47/7be41556bfbb6917069d6a6634bb7dd5e163ba445b783a90d40f5ac7e3a7/aiohttp-3.13.5-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:ab2899f9fa2f9f741896ebb6fa07c4c883bfa5c7f2ddd8cf2aafa86fa981b2d2", size = 500258, upload-time = "2026-03-31T21:57:39.923Z" },
{ url = "https://files.pythonhosted.org/packages/67/84/c9ecc5828cb0b3695856c07c0a6817a99d51e2473400f705275a2b3d9239/aiohttp-3.13.5-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a60eaa2d440cd4707696b52e40ed3e2b0f73f65be07fd0ef23b6b539c9c0b0b4", size = 1749199, upload-time = "2026-03-31T21:57:41.938Z" },
{ url = "https://files.pythonhosted.org/packages/f0/d3/3c6d610e66b495657622edb6ae7c7fd31b2e9086b4ec50b47897ad6042a9/aiohttp-3.13.5-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:55b3bdd3292283295774ab585160c4004f4f2f203946997f49aac032c84649e9", size = 1721013, upload-time = "2026-03-31T21:57:43.904Z" },
{ url = "https://files.pythonhosted.org/packages/49/a0/24409c12217456df0bae7babe3b014e460b0b38a8e60753d6cb339f6556d/aiohttp-3.13.5-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:c2b2355dc094e5f7d45a7bb262fe7207aa0460b37a0d87027dcf21b5d890e7d5", size = 1781501, upload-time = "2026-03-31T21:57:46.285Z" },
{ url = "https://files.pythonhosted.org/packages/98/9d/b65ec649adc5bccc008b0957a9a9c691070aeac4e41cea18559fef49958b/aiohttp-3.13.5-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:b38765950832f7d728297689ad78f5f2cf79ff82487131c4d26fe6ceecdc5f8e", size = 1878981, upload-time = "2026-03-31T21:57:48.734Z" },
{ url = "https://files.pythonhosted.org/packages/57/d8/8d44036d7eb7b6a8ec4c5494ea0c8c8b94fbc0ed3991c1a7adf230df03bf/aiohttp-3.13.5-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b18f31b80d5a33661e08c89e202edabf1986e9b49c42b4504371daeaa11b47c1", size = 1767934, upload-time = "2026-03-31T21:57:51.171Z" },
{ url = "https://files.pythonhosted.org/packages/31/04/d3f8211f273356f158e3464e9e45484d3fb8c4ce5eb2f6fe9405c3273983/aiohttp-3.13.5-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:33add2463dde55c4f2d9635c6ab33ce154e5ecf322bd26d09af95c5f81cfa286", size = 1566671, upload-time = "2026-03-31T21:57:53.326Z" },
{ url = "https://files.pythonhosted.org/packages/41/db/073e4ebe00b78e2dfcacff734291651729a62953b48933d765dc513bf798/aiohttp-3.13.5-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:327cc432fdf1356fb4fbc6fe833ad4e9f6aacb71a8acaa5f1855e4b25910e4a9", size = 1705219, upload-time = "2026-03-31T21:57:55.385Z" },
{ url = "https://files.pythonhosted.org/packages/48/45/7dfba71a2f9fd97b15c95c06819de7eb38113d2cdb6319669195a7d64270/aiohttp-3.13.5-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:7c35b0bf0b48a70b4cb4fc5d7bed9b932532728e124874355de1a0af8ec4bc88", size = 1743049, upload-time = "2026-03-31T21:57:57.341Z" },
{ url = "https://files.pythonhosted.org/packages/18/71/901db0061e0f717d226386a7f471bb59b19566f2cae5f0d93874b017271f/aiohttp-3.13.5-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:df23d57718f24badef8656c49743e11a89fd6f5358fa8a7b96e728fda2abf7d3", size = 1749557, upload-time = "2026-03-31T21:57:59.626Z" },
{ url = "https://files.pythonhosted.org/packages/08/d5/41eebd16066e59cd43728fe74bce953d7402f2b4ddfdfef2c0e9f17ca274/aiohttp-3.13.5-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:02e048037a6501a5ec1f6fc9736135aec6eb8a004ce48838cb951c515f32c80b", size = 1558931, upload-time = "2026-03-31T21:58:01.972Z" },
{ url = "https://files.pythonhosted.org/packages/30/e6/4a799798bf05740e66c3a1161079bda7a3dd8e22ca392481d7a7f9af82a6/aiohttp-3.13.5-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:31cebae8b26f8a615d2b546fee45d5ffb76852ae6450e2a03f42c9102260d6fe", size = 1774125, upload-time = "2026-03-31T21:58:04.007Z" },
{ url = "https://files.pythonhosted.org/packages/84/63/7749337c90f92bc2cb18f9560d67aa6258c7060d1397d21529b8004fcf6f/aiohttp-3.13.5-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:888e78eb5ca55a615d285c3c09a7a91b42e9dd6fc699b166ebd5dee87c9ccf14", size = 1732427, upload-time = "2026-03-31T21:58:06.337Z" },
{ url = "https://files.pythonhosted.org/packages/98/de/cf2f44ff98d307e72fb97d5f5bbae3bfcb442f0ea9790c0bf5c5c2331404/aiohttp-3.13.5-cp312-cp312-win32.whl", hash = "sha256:8bd3ec6376e68a41f9f95f5ed170e2fcf22d4eb27a1f8cb361d0508f6e0557f3", size = 433534, upload-time = "2026-03-31T21:58:08.712Z" },
{ url = "https://files.pythonhosted.org/packages/aa/ca/eadf6f9c8fa5e31d40993e3db153fb5ed0b11008ad5d9de98a95045bed84/aiohttp-3.13.5-cp312-cp312-win_amd64.whl", hash = "sha256:110e448e02c729bcebb18c60b9214a87ba33bac4a9fa5e9a5f139938b56c6cb1", size = 460446, upload-time = "2026-03-31T21:58:10.945Z" },
{ url = "https://files.pythonhosted.org/packages/ef/f0/f81190ba488cd106c2fc6d92680e56bb223bbbbf1e6908c2617011290112/aiohttp-3.14.0-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:692e409052e7436029bbb32977cd7c5bf806ac5fa4085b973996785ffadad33c", size = 760606, upload-time = "2026-06-01T19:36:39.054Z" },
{ url = "https://files.pythonhosted.org/packages/f6/54/444d37eebf0f15db661ca44ec7caf93962f3c5ca92eb4c9a5d888b70aaa2/aiohttp-3.14.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:40af7ebe53c7990e110dc4ad03566b12c3ac996254298a3d39046dd69cfcb2c2", size = 514677, upload-time = "2026-06-01T19:36:42.408Z" },
{ url = "https://files.pythonhosted.org/packages/d0/d1/da280e23321c132c0a3fa7c8cc2830621d79174edc64c829443346489a36/aiohttp-3.14.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:02cb2ffbb7da32f82e21ad9952669c45bd88a80e0878264c2f59fe1c6fb2badd", size = 510155, upload-time = "2026-06-01T19:36:44.072Z" },
{ url = "https://files.pythonhosted.org/packages/09/b8/2e36d54d0991ec5bba451444004591ee0af58cb1662a3a81c562878b9c1f/aiohttp-3.14.0-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:2e2514cb7195f6d7c219339635bea71ae47d1569b051300d32df9dcfabcdb869", size = 1699947, upload-time = "2026-06-01T19:36:45.762Z" },
{ url = "https://files.pythonhosted.org/packages/57/95/a31d8ea1a0b9ecc084f5a7dd0b431ce64ef585918bb7bdc82afe11843877/aiohttp-3.14.0-cp310-cp310-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:30e8b7eeb42d02c120ca90d6c6e076a221a16b70a6dac9ae44c7ab5104cc7fe4", size = 1664364, upload-time = "2026-06-01T19:36:47.653Z" },
{ url = "https://files.pythonhosted.org/packages/01/f6/5de3ddffc87a9e8d09b3be38fbd6dd1a736b2ad477a7e787dcb85f57f338/aiohttp-3.14.0-cp310-cp310-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:63e38be0d75a654deaa06be32fb4cab883a4222940be1d05861b6717679cbadb", size = 1761186, upload-time = "2026-06-01T19:36:49.355Z" },
{ url = "https://files.pythonhosted.org/packages/33/8c/03c5438ec35d7e3a4f33fe895d6c3ec7540a7cec46065f21851211e1ee4d/aiohttp-3.14.0-cp310-cp310-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:1210d4c87cc00128160c7384ab41877a701295b97cffa6362f908a49b6e8a7ca", size = 1849727, upload-time = "2026-06-01T19:36:51.478Z" },
{ url = "https://files.pythonhosted.org/packages/22/32/5a05303b0874458920b73f48b8779cc3a93d503f121b38dcc0456dbd698c/aiohttp-3.14.0-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:1a78a77366ed158a0a54b076990e575d7b7cdb728cbfd02711eadab150f2269f", size = 1708197, upload-time = "2026-06-01T19:36:53.241Z" },
{ url = "https://files.pythonhosted.org/packages/7d/62/478f169488d61414c0a05e7fe423b59ae3d9dcc933d1f0e4acc2c5d5bc3e/aiohttp-3.14.0-cp310-cp310-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:f4d2038c64f36df96cfd3fa0937910e231eafbf897e70a06c155a817bb632fa6", size = 1578147, upload-time = "2026-06-01T19:36:55.154Z" },
{ url = "https://files.pythonhosted.org/packages/1d/af/b20af85765658972d3337834bd5eebba91b962794f2b4fc3e0ee8c85c0e1/aiohttp-3.14.0-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:4714c70067a08b604d0bf3bc4dfdf82e52944afab41d0428d460862763d2f79b", size = 1665836, upload-time = "2026-06-01T19:36:56.94Z" },
{ url = "https://files.pythonhosted.org/packages/8d/a3/771879cfd59948f4544b172189048905feff802f20f1c6c5411e998a3e06/aiohttp-3.14.0-cp310-cp310-musllinux_1_2_armv7l.whl", hash = "sha256:f79bfd2847513a7ac801bbafd1de02348a37926ac439eeb4bfe96fcff4eada15", size = 1680335, upload-time = "2026-06-01T19:36:58.642Z" },
{ url = "https://files.pythonhosted.org/packages/f4/16/582e36ad1d32133cd40659f3bc98e71c22179665a1cfbbb4713bce339c06/aiohttp-3.14.0-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:25e9f1d2465a210d60edb64d7b204a147e85d4c194eecef3d1604fb5ace678ce", size = 1731180, upload-time = "2026-06-01T19:37:00.583Z" },
{ url = "https://files.pythonhosted.org/packages/11/bc/80708fe3f64a07a2c306a42fc7b009118a952709761d215f6d1b4c57195b/aiohttp-3.14.0-cp310-cp310-musllinux_1_2_riscv64.whl", hash = "sha256:b5314743ebe926c2fda35d0a298c565c885505f6635c2a30936363404cf274a7", size = 1565805, upload-time = "2026-06-01T19:37:02.446Z" },
{ url = "https://files.pythonhosted.org/packages/57/8f/8d25897f8273a32fe4ad40a8885eec4f397377ed46e8e383078169f60316/aiohttp-3.14.0-cp310-cp310-musllinux_1_2_s390x.whl", hash = "sha256:28eee8de1d69711c53116df8202f1c2aa0e3f80ef912a88fc18d159d53e7110b", size = 1742496, upload-time = "2026-06-01T19:37:04.222Z" },
{ url = "https://files.pythonhosted.org/packages/9f/7d/c341d32ab2dec56c8478740695743dc6c21b383cace9376a3eab16311a07/aiohttp-3.14.0-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:89ed35666c95d3efe1955056afcde09e62a57a34e2a4398b17f9f6c1564f0b25", size = 1691240, upload-time = "2026-06-01T19:37:06.277Z" },
{ url = "https://files.pythonhosted.org/packages/37/0f/a81207dd7a2d4a4f645b3a3f8b5a1da1159dc63117ffb137b698fd6df50f/aiohttp-3.14.0-cp310-cp310-win32.whl", hash = "sha256:5e4646e9a6af29af354204011bf5769cb0276ec5b64653e42f90b3e13845169f", size = 454686, upload-time = "2026-06-01T19:37:07.96Z" },
{ url = "https://files.pythonhosted.org/packages/7f/ae/842357f2afb9c915715c6f5775239d987f5d0f845abf7675fa794e0a9d40/aiohttp-3.14.0-cp310-cp310-win_amd64.whl", hash = "sha256:22a8d06f204e0518a586d770032db3c7043c9ba3693081b3e3ad425e1458d594", size = 478677, upload-time = "2026-06-01T19:37:09.652Z" },
{ url = "https://files.pythonhosted.org/packages/6b/d1/330fb22c9535ec177b52396905131c6e39447244b6ca876262939af668ef/aiohttp-3.14.0-cp310-cp310-win_arm64.whl", hash = "sha256:4acfc34bd4d3c58754fc9f22ff1b5e92aabce68f3d4bf7b71a0b732d9bceb78a", size = 450364, upload-time = "2026-06-01T19:37:11.279Z" },
{ url = "https://files.pythonhosted.org/packages/67/47/7727bfe8db93f8835a001bd4359d8480cc68d1259b8bce334668f8be97bd/aiohttp-3.14.0-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:54bf3522d6f7351e55f89a62d5c2bf138ad557b031670266c5df604ae88e0b5a", size = 759147, upload-time = "2026-06-01T19:37:12.918Z" },
{ url = "https://files.pythonhosted.org/packages/eb/f2/cd3fedff6fade73d71df9ec908c210cec518ef90fd00289250684b90aecf/aiohttp-3.14.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:0746d9fb0ac4fdef643a84494efe3f06d50335dd8c7a530228b86448aae0a803", size = 513705, upload-time = "2026-06-01T19:37:14.633Z" },
{ url = "https://files.pythonhosted.org/packages/5a/fe/49746b6b610144a06323bebd8e1211a390310d8c69b98dd6d52df341bc3e/aiohttp-3.14.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:9f3a96b6d39a4872222beee72e1df41d2ff886ae96152cf3e757ef8c5673ef0e", size = 509627, upload-time = "2026-06-01T19:37:16.385Z" },
{ url = "https://files.pythonhosted.org/packages/4c/3f/28f2f6cf3d5c0e7b01b27140d0e7873fd11fb341169ad3ce78ad04aba628/aiohttp-3.14.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d336820adbb914debbc90a1d8c1bfc4bea55996aecf64866a989d35d1f9fd903", size = 1769293, upload-time = "2026-06-01T19:37:18.067Z" },
{ url = "https://files.pythonhosted.org/packages/97/6f/2e5f1b525d5474b12b3c60abf733a755845f3bceff21542081ada515f837/aiohttp-3.14.0-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:71b2604c9bfc1b115547d63a094d5244b3f02799833513a99a68aaa7b167c4cb", size = 1732363, upload-time = "2026-06-01T19:37:20.138Z" },
{ url = "https://files.pythonhosted.org/packages/a8/ce/596120faa85ca7b19cd061e3f2f3be23aa8f11a0aedf9191db9e0da1bd76/aiohttp-3.14.0-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:610d68800435903e303ca0542b9d3e4eb72a12ff33a6d471a070c1d81eebd3c2", size = 1840375, upload-time = "2026-06-01T19:37:22.104Z" },
{ url = "https://files.pythonhosted.org/packages/72/3c/a7ffe05a757a4a7867643da69357ec41f506879fbd1b231d2ed90af246b2/aiohttp-3.14.0-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:514db9a79337068981ee2137310283a07b4b885c584991097a91a4da419bcb81", size = 1921484, upload-time = "2026-06-01T19:37:24.068Z" },
{ url = "https://files.pythonhosted.org/packages/93/fa/2c861170bbd4a491de93a69e081db1d971092569e0d593a98ef62c384dc1/aiohttp-3.14.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c452d17eeb95d563fc8b936f3050301dbd1d268126c4632d8b70ede9696202ee", size = 1774153, upload-time = "2026-06-01T19:37:26.256Z" },
{ url = "https://files.pythonhosted.org/packages/9d/da/1d2f5a165f47ec9b1f69d37b8b977fdc4d501aa72ffb7930db27bb9e49ea/aiohttp-3.14.0-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:ed94a81506e3d1bdbad5108f497a58f2a2354aedb4ca314d5326f07d1fd1ac2d", size = 1632569, upload-time = "2026-06-01T19:37:28.192Z" },
{ url = "https://files.pythonhosted.org/packages/46/1d/7a6e295c4257252f70f69e90864fdad74b6a1293054fb3f9e65a15de6d63/aiohttp-3.14.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:1394dce36e0f0d260ac0b555a654de19cb989f3c1b8bdd24f505314dfea18a00", size = 1740325, upload-time = "2026-06-01T19:37:30.08Z" },
{ url = "https://files.pythonhosted.org/packages/f1/7e/e1899b1ca3ec62f1eab2a5cbde14039b97493f7f53eb88d9b668562ffa8d/aiohttp-3.14.0-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:d1467d1e7b48a73ca7237e0ee4335f3d02b923dbc27b82fd254bc301c97d4026", size = 1748691, upload-time = "2026-06-01T19:37:32.211Z" },
{ url = "https://files.pythonhosted.org/packages/ec/54/4e6b61c1fe7d3433f82bcc6bd7e4d7c683a742a10c9b12a025fd3695c047/aiohttp-3.14.0-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:6a5f3532125233c261cf61f32df4059cfcf482eb793c7d3db8452e3142028b86", size = 1814477, upload-time = "2026-06-01T19:37:34.173Z" },
{ url = "https://files.pythonhosted.org/packages/9c/38/86fd51be2e08d8e45c83d879d255f10391903cd9fe2a16512f7591a15873/aiohttp-3.14.0-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:3ea81eb518a2ecb319d8ec6d1424a37c773f6634bd87d6985eb606b2faac419f", size = 1623393, upload-time = "2026-06-01T19:37:36.281Z" },
{ url = "https://files.pythonhosted.org/packages/78/49/466e947a42a88ee23c486d036e7e5d1b097f1bafd8084ad9c9a0a92f0f43/aiohttp-3.14.0-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:32e735c3182de7b64f6941a4ede48b38c7f47d9437bd615dd30b5bda8fa1bc93", size = 1824097, upload-time = "2026-06-01T19:37:38.421Z" },
{ url = "https://files.pythonhosted.org/packages/f3/89/35f3410bc284682338a1be6b6ea0c5abfa05f063942cfaa9256608440434/aiohttp-3.14.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:c21ca9a1c63d4509158f478aeb9d02914dcc52adc68d1bc9dee2452284ee5996", size = 1764790, upload-time = "2026-06-01T19:37:40.755Z" },
{ url = "https://files.pythonhosted.org/packages/42/80/2d4291bd5724d3d17e5951aff5a3e02281483fb47295f0788276ee66cd73/aiohttp-3.14.0-cp311-cp311-win32.whl", hash = "sha256:19ca5fc84130675ba11c6ca5c7da5cb65f7bf8a32cdd2b616bf49cd334688aae", size = 454176, upload-time = "2026-06-01T19:37:42.837Z" },
{ url = "https://files.pythonhosted.org/packages/59/ed/41d0ad4f6ececffc32bdf1f7b494e5498f7ca5c849ea2e3cc9bbd1668251/aiohttp-3.14.0-cp311-cp311-win_amd64.whl", hash = "sha256:d488e6e9d3bb8ba5ae7066d5be885ae9670eba021b8c6ccb9a3a568e6b19d6e5", size = 479334, upload-time = "2026-06-01T19:37:44.776Z" },
{ url = "https://files.pythonhosted.org/packages/d1/86/c0b5e305c770053f8c3d069bb52b8196917ba91949d1962d52eb307fb0d2/aiohttp-3.14.0-cp311-cp311-win_arm64.whl", hash = "sha256:8b93618102caf12801638a01a2b478a55410ddd71bd41cfaf6f707953a49ac43", size = 450262, upload-time = "2026-06-01T19:37:46.461Z" },
{ url = "https://files.pythonhosted.org/packages/89/97/2b6889bfb6b6847520d50d95eb8c4307a45e28aaca39faf4a9454b3d1b2f/aiohttp-3.14.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:b29518c9c2ec7e373e68259206a137c7f4f5439c58baaec4b5ab3ab799850a4e", size = 750194, upload-time = "2026-06-01T19:37:48.164Z" },
{ url = "https://files.pythonhosted.org/packages/21/e2/62634b7fff918ed98c3c6b2f0e70d520f7f28846cb412d451b04354c6459/aiohttp-3.14.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:dbec68ce61b64cb73cab4d33df9433427b1713c8bcccb181dce695c1b6f8e87c", size = 506966, upload-time = "2026-06-01T19:37:50.014Z" },
{ url = "https://files.pythonhosted.org/packages/dd/fb/5ce075150828c797a5106f1c2fb26034e709d4289b9d2bf8b07f1e59fac6/aiohttp-3.14.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:3cdf534aa455593e589302990c5097aa5c92c06c4262a20da22934f9186a5fff", size = 507527, upload-time = "2026-06-01T19:37:51.96Z" },
{ url = "https://files.pythonhosted.org/packages/01/d5/405a0ae4e6b081754a3609c1c97c63a950e000a2def16046f1e736933a0e/aiohttp-3.14.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:cb6c657104393b5fbff01a5f59b2023db74058a8077d94475d6c25d03882a108", size = 1762420, upload-time = "2026-06-01T19:37:53.839Z" },
{ url = "https://files.pythonhosted.org/packages/ae/1d/e05a7c896b15a6bc6fb8fc5319eb437861c2c49c34559ef928add6590315/aiohttp-3.14.0-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:46fbbec4e4fab7428d4396a3823f9320e4560aa3113b89eeebce712c27c9ed5a", size = 1733672, upload-time = "2026-06-01T19:37:55.791Z" },
{ url = "https://files.pythonhosted.org/packages/cc/22/a72f7c459e195fa41bf4f7abd1f925b91fe91f8097e51c654229ba144a33/aiohttp-3.14.0-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:2c2c7e05dd5335b298085abf45ddf98673934c3ee1c083d0b9ea13d4186ad500", size = 1805064, upload-time = "2026-06-01T19:37:57.931Z" },
{ url = "https://files.pythonhosted.org/packages/80/50/e85bdaba0be59ca4838005ebfef4048fcdd5f35a02b07057a9a123394440/aiohttp-3.14.0-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:3c7139100fbaae76515b73051d8f0aa3a3ff02e415eec8a8eee8e2223d9ba955", size = 1902125, upload-time = "2026-06-01T19:38:00.225Z" },
{ url = "https://files.pythonhosted.org/packages/19/d8/51de5c6b971c27bb1ef620293b8d1ca611ec78736b34b3f6ccf68e4c8785/aiohttp-3.14.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:78d6f9286a629ce52728430afe18f8ed2b6c39a1fddb3802d7244b9983910ad2", size = 1783112, upload-time = "2026-06-01T19:38:02.641Z" },
{ url = "https://files.pythonhosted.org/packages/73/ae/b4402bfde77e43dfb1b6ccff83c7b7ab63ed06b50c4754f0c5423fb374fe/aiohttp-3.14.0-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:cc3c3e12cdaeb92d7dcf13db00e9f6b1956b910e47256e696df1cfa946d02159", size = 1586356, upload-time = "2026-06-01T19:38:04.637Z" },
{ url = "https://files.pythonhosted.org/packages/bc/05/750a3265ca4dc54a460bd0cb1121a8f2ce9171fce4a135fb47ea7fd594d2/aiohttp-3.14.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:4d6a998191f5ebe3b8c28463ff72bc030250008b3193c402464efadd08b5ca02", size = 1723119, upload-time = "2026-06-01T19:38:06.713Z" },
{ url = "https://files.pythonhosted.org/packages/37/01/8c0812c50b3b1b1c37b323bf170d6be8847a8f234060485b7d1e71953f60/aiohttp-3.14.0-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:0fc2b75ae8d169d853be2862d960be8550da6c5c65711d5476407eb3fdb006bd", size = 1757216, upload-time = "2026-06-01T19:38:08.736Z" },
{ url = "https://files.pythonhosted.org/packages/47/2a/50fb98028a26887cbe48dcc1df92a90825615bc73b5584301304090cded8/aiohttp-3.14.0-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:16eee56bcc72d04600bc56c1759982c2385ec0b41d3fd3521f836bf64a0957ef", size = 1770500, upload-time = "2026-06-01T19:38:11.111Z" },
{ url = "https://files.pythonhosted.org/packages/bd/32/0ffd598a2fa2b9a423daf242e700cfdabda35d6e602394ad9ae58972c1c7/aiohttp-3.14.0-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:5a2e7ca615c3ddc15b82687e05a624e5f5cba3f1d6c20cb81172d70ea498451e", size = 1576224, upload-time = "2026-06-01T19:38:13.391Z" },
{ url = "https://files.pythonhosted.org/packages/0b/f9/b9fc381dd9b66afb33f2634c40e229d106467be0afcabe79648631ab6712/aiohttp-3.14.0-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:f0b7b8bbbec3ce9467ee0ebe334622fd90624f593edd3136c567811453fc4fae", size = 1794252, upload-time = "2026-06-01T19:38:15.498Z" },
{ url = "https://files.pythonhosted.org/packages/a8/fb/05d9214c975f23225a8cd5c439325e338c7c377b315480ef3871db51f54e/aiohttp-3.14.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:5ba10966d4f03dd96a14365be4b8e37c327c76f11c3ca867116966cdd9f98066", size = 1760193, upload-time = "2026-06-01T19:38:17.624Z" },
{ url = "https://files.pythonhosted.org/packages/d9/4b/02992fc4fb9e1b6673ee3f888a8e587a6447afda1f6f4aca776c148c2876/aiohttp-3.14.0-cp312-cp312-win32.whl", hash = "sha256:101df7779c80c0636014a6b2c6642acd3efb5b355d48347c9d7dfb720aee9430", size = 448650, upload-time = "2026-06-01T19:38:19.545Z" },
{ url = "https://files.pythonhosted.org/packages/39/e9/246532214c3abda518477cbaaf16d420295ad8effa5233844cbb38f299ab/aiohttp-3.14.0-cp312-cp312-win_amd64.whl", hash = "sha256:b0a5747586d4467efd1f932710b269131c9717a872dce082cd92a00c1c13123a", size = 476145, upload-time = "2026-06-01T19:38:21.505Z" },
{ url = "https://files.pythonhosted.org/packages/2b/c3/63f8c20090048915711598b0adf475b149216d736157961de06480a45b15/aiohttp-3.14.0-cp312-cp312-win_arm64.whl", hash = "sha256:5f1c5be60add78fabb4aacd13c5a348ae79d2fcbfc7fa78da8f1eb192273b370", size = 444250, upload-time = "2026-06-01T19:38:24.027Z" },
]
[[package]]
@@ -1816,7 +1820,7 @@ test = [
[package.metadata]
requires-dist = [
{ name = "aiohttp", specifier = ">=3.13.4,<4" },
{ name = "aiohttp", specifier = ">=3.14.0,<4" },
{ name = "aiohttp-swagger3", specifier = ">=0.9.0,<1" },
{ name = "animeapi-py", specifier = ">=0.6.0" },
{ name = "appdirs", specifier = ">=1.4.4,<2" },