style: clean up prose

This commit is contained in:
imSp4rky
2026-08-19 13:45:58 -06:00
parent 54adb82746
commit 29d0828c33
40 changed files with 109 additions and 110 deletions
+2 -2
View File
@@ -23,7 +23,7 @@ from unshackle.core.utilities import close_debug_logger, init_debug_logger
@click.option("-v", "--version", is_flag=True, default=False, help="Print version information.")
@click.option("-d", "--debug", is_flag=True, default=False, help="Enable DEBUG level logs and JSON debug logging.")
def main(version: bool, debug: bool) -> None:
"""unshackle—Modular Movie, TV, and Music Archival Software."""
"""unshackle: Modular Movie, TV, and Music Archival Software."""
debug_logging_enabled = debug or config.debug
logging.basicConfig(
@@ -80,7 +80,7 @@ def main(version: bool, debug: bool) -> None:
latest_version = UpdateChecker.check_for_updates_sync(__version__)
if latest_version:
console.print(
f"\n[yellow]⚠️ Update available![/yellow] "
f"\n[yellow]Update available![/yellow] "
f"Current: {__version__} → Latest: [green]{latest_version}[/green]",
justify="center",
)
+1 -1
View File
@@ -2,7 +2,7 @@
Instantiates a CDM object (local or remote) given a resolved device name.
Name resolution (quality-based, profile-based, DRM-type) is the caller's
responsibility — this module only handles the instantiation step.
responsibility; this module only handles the instantiation step.
"""
from __future__ import annotations
+1 -1
View File
@@ -640,7 +640,7 @@ def download(
RnetSession preserves TLS fingerprinting for services that need it.
segmented: If downloads are segments or parts of one bigger file.
part_offset: Byte offset to write at within a pre-allocated file. When set
(with `part_end`), enables part mode for parallel ranged downloads —
(with `part_end`), enables part mode for parallel ranged downloads:
no truncate, no skip-if-exists, no control file; emits only `advance`
events; retries resume mid-part via Range.
part_end: Inclusive end byte of the part. Required when `part_offset` is set.
-1
View File
@@ -872,7 +872,6 @@ def describe(code: int) -> str | None:
if __name__ == "__main__":
# ponytail: one check, signed and unsigned forms resolve to the same entry
assert describe(0x8004C065) == describe(-2147172251)
assert "DEVCERT_REVOKED" in describe(-2147172251)
assert describe(-1021) is None # non-DRM_E service code
+1 -1
View File
@@ -1177,7 +1177,7 @@ class DASH:
drm.append(PlayReady(pssh=pr_pssh, kid=kid, pssh_b64=pr_pssh_b64))
elif urn == ClearKeyCENC.urn:
# W3C EME ClearKey (org.w3.clearkey) — match the scheme UUID alone,
# W3C EME ClearKey (org.w3.clearkey): match the scheme UUID alone,
# value="ClearKey1.0" is spec'd (DASH-IF CCP) but not required in the wild
kid_attr = protection.get("default_KID") or protection.get("{urn:mpeg:cenc:2013}default_KID")
kid = None
+1 -1
View File
@@ -355,7 +355,7 @@ class HLS:
seg_uri = urljoin(variant_url, variant.segments[0].uri)
# Download only the first 8KB — SPS is always near the start of the first TS packet
# Download only the first 8KB: SPS is always near the start of the first TS packet
res = session.get(seg_uri, headers={"Range": "bytes=0-8191"})
data = res.content
+1 -1
View File
@@ -215,7 +215,7 @@ class ISM:
iv_size=iv_size,
)
except (NotImplementedError, ValueError, struct.error) as e:
# Unsupported codec, malformed CodecPrivateData or out-of-range field —
# Unsupported codec, malformed CodecPrivateData or out-of-range field:
# fall back to raw concatenation rather than aborting the download.
log_event(
"manifest_ism_init_unsupported",
+5 -5
View File
@@ -46,7 +46,7 @@ TRACK_IN_MOVIE = 0x2
TRACK_IN_PREVIEW = 0x4
SELF_CONTAINED = 0x1
# Fixed creation/modification time — deterministic output (no wall clock).
# Fixed creation/modification time for deterministic output (no wall clock).
EPOCH = 0
NAL_START_CODE = b"\x00\x00\x00\x01"
@@ -96,7 +96,7 @@ def split_nal_units(codec_private_data: bytes) -> list[bytes]:
def remove_emulation_prevention(data: bytes) -> bytes:
"""Strip H.26x emulation-prevention bytes (the 0x03 in any 00 00 03 run).
The byte after a consumed escape is data — even another 0x03 — so the scan
The byte after a consumed escape is data, even another 0x03, so the scan
must skip past it rather than re-examine (a naive trailing-window check
over-strips consecutive escapes and shifts every later bit position).
"""
@@ -611,10 +611,10 @@ def build_dec3(codec_private_data: bytes) -> Optional[bytes]:
"""Build a dec3 (EC-3 specific) box from Smooth EC-3 CodecPrivateData.
Smooth EC-3 CodecPrivateData ([MS-SSTR] AudioTag 65534) serializes a
WAVEFORMATEXTENSIBLE — sometimes the full structure, sometimes only its
extension (samples-per-block + channel mask + DD+ SubFormat GUID) — with
WAVEFORMATEXTENSIBLE, sometimes the full structure, sometimes only its
extension (samples-per-block + channel mask + DD+ SubFormat GUID), with
the raw dec3 payload (ETSI TS 102 366 F.6) after the GUID. Returns None
when the GUID is absent — decoders still sync from EC-3 frames in mdat.
when the GUID is absent; decoders still sync from EC-3 frames in mdat.
"""
guid_at = codec_private_data.find(DOLBY_DIGITAL_PLUS_GUID)
if guid_at != -1 and len(codec_private_data) > guid_at + 16:
+2 -2
View File
@@ -431,7 +431,7 @@ def validate_enrichments(
tmdb_votes[provider_name] = ext.tmdb_id
if len(set(tmdb_votes.values())) <= 1:
return enrichments # all agree or only one voted — no conflict
return enrichments # all agree or only one voted, no conflict
value_counts = Counter(tmdb_votes.values())
most_common_val, most_common_count = value_counts.most_common(1)[0]
@@ -439,7 +439,7 @@ def validate_enrichments(
if most_common_count > 1:
anchor_tmdb_id = most_common_val
else:
# No majority — pick the most authoritative provider
# No majority, so pick the most authoritative provider
best_provider = min(
tmdb_votes.keys(),
key=lambda name: authority.get(name, 99),
+1 -1
View File
@@ -206,7 +206,7 @@ class TVDBProvider(MetadataProvider):
return cached
episodes: list[dict] = []
for page in range(20): # ponytail: hard page cap, 500 eps/page covers any real series
for page in range(20):
data = self.api_get(f"/series/{tvdb_id}/episodes/{order}", {"page": page})
if data is None and page:
# a partial listing would renumber episodes wrongly
+1 -1
View File
@@ -24,7 +24,7 @@ class ProtonVPN(Proxy):
Proton VPN HTTPS proxy provider.
Authenticates via TV login (a self-sustaining session cached at <cache>/vpn/protonvpn.json, the
only refreshable kind) or an exported account.proton.me cookie session (AUTH-<UID>, access only —
only refreshable kind) or an exported account.proton.me cookie session (AUTH-<UID>, access only,
re-export on expiry). Resolves a server by country/city, mints short-lived proxy credentials, and
returns an authenticated HTTPS proxy URL (https://user:pass@server:4443).
+1 -1
View File
@@ -736,7 +736,7 @@ class RemoteService:
def create_drm_stub(drm_type: str, kid_hexes: list[str]) -> Any:
"""Create a DRM object stub matching the type the server actually used.
For server_cdm mode, this is only used for display — keys are already
For server_cdm mode, this is only used for display; keys are already
resolved. We build a minimal DRM object that holds content_keys.
"""
from uuid import UUID
+3 -3
View File
@@ -95,12 +95,12 @@ def resolve_service_repo(spec: str, *, ttl: int = DEFAULT_TTL, force: bool = Fal
force_sync(dest, stamp)
elif is_stale(stamp, ttl):
pull(dest, stamp)
return dest # ponytail: git IS the cache layer — no bespoke fetch/integrity code
return dest
def clone(url: str, branch: Optional[str], dest: Path, stamp: Path) -> Optional[Path]:
if not binaries.Git:
log.error("git not found on PATH — cannot fetch service repo %s", url)
log.error("git not found on PATH; cannot fetch service repo %s", url)
return None
dest.parent.mkdir(parents=True, exist_ok=True)
args = [str(binaries.Git), "clone", "--depth", "1"]
@@ -122,7 +122,7 @@ def pull(dest: Path, stamp: Path) -> None:
if not binaries.Git:
write_stamp(stamp)
return
# never clobber local edits — refuse to refresh a dirty clone and let the caller exit cleanly
# never clobber local edits: refuse to refresh a dirty clone and let the caller exit cleanly
if is_dirty(dest):
raise DirtyServiceRepo(dest)
try:
+2 -2
View File
@@ -755,11 +755,11 @@ class RnetSession:
return self.request(method, url, **send_kwargs)
def mount(self, prefix: str, adapter: Any) -> None:
"""No-op — rnet handles TLS and connection pooling natively."""
"""No-op; rnet handles TLS and connection pooling natively."""
pass
def close(self) -> None:
"""No-op — rnet manages its own resources."""
"""No-op; rnet manages its own resources."""
pass
+1 -1
View File
@@ -6,7 +6,7 @@ hvc1, with DV advertised only via SUPPLEMENTAL-CODECS. The fMP4 carries valid DV
but the container does not signal DV, so muxing the MP4 directly produces an MKV that
mediainfo and DV-capable TVs see as plain HDR10/HDR10+.
The RPU is already valid — only the container's DV signaling is lost. Demuxing the
The RPU is already valid; only the container's DV signaling is lost. Demuxing the
elementary HEVC stream (ffmpeg -c:v copy) exposes the in-stream RPU to mkvmerge, which then
signals DV in the muxed MKV. No dovi_tool extract/inject round-trip is needed.
"""
+5 -5
View File
@@ -8,7 +8,7 @@ requested pair and orders them by rank; ``run_conversion`` tries each in turn (a
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
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).
"""
@@ -113,7 +113,7 @@ def subtitleedit_args(
# Styled SubStation formats flattened to SRT lose positioning/colours/italics.
# Never performed automatically — only when the user explicitly forces a target format.
# Never performed automatically, only when the user explicitly forces a target format.
LOSSY_DOWNCONVERTS: frozenset[tuple[Codec, Codec]] = frozenset(
{
(Codec.SubStationAlpha, Codec.SubRip),
@@ -188,7 +188,7 @@ class SubtitleEditBackend:
class Pysubs2Backend:
"""pysubs2 — pure Python, broad format support, best fidelity for SSA/ASS (native style model)."""
"""pysubs2: pure Python, broad format support, best fidelity for SSA/ASS (native style model)."""
name = "pysubs2"
formats = frozenset(PYSUBS2_FORMATS)
@@ -209,7 +209,7 @@ class Pysubs2Backend:
class SubbyBackend:
"""subby — purpose-built for streaming subs. WebVTT/fVTT/SAMI -> SRT + CommonIssuesFixer cleanup."""
"""subby: purpose-built for streaming subs. WebVTT/fVTT/SAMI -> SRT + CommonIssuesFixer cleanup."""
name = "subby"
reads = frozenset({Codec.WebVTT, Codec.fVTT, Codec.SAMI})
@@ -248,7 +248,7 @@ class SubbyBackend:
class PycaptionBackend:
"""pycaption — last resort. Note: flattens positioning/italics (devine #39), so ranked last."""
"""pycaption: last resort. Flattens positioning/italics (devine #39), so ranked last."""
name = "pycaption"
reads = frozenset({Codec.SubRip, Codec.TimedTextMarkupLang, Codec.WebVTT, Codec.SAMI, Codec.fTTML, Codec.fVTT})
+1 -1
View File
@@ -667,7 +667,7 @@ class Track:
def base_kwargs_from_dict(data: dict[str, Any]) -> dict[str, Any]:
"""Build the shared Track constructor kwargs from a ``to_dict()`` payload.
DRM is not reconstructed here — ``to_dict`` does not serialise it, and the import
DRM is not reconstructed here: ``to_dict`` does not serialise it, and the import
flow attaches the licensed DRM + content keys separately.
"""
return {
+2 -2
View File
@@ -433,7 +433,7 @@ class Video(Track):
if not vui:
return None
# Skip the rewrite when the bitstream VUI already matches the target — avoids a full
# Skip the rewrite when the bitstream VUI already matches the target, which avoids a full
# bitstream pass on services that already ship correct colour metadata
expected = {
Video.Range.HDR10: ("bt2020", "smpte2084", "bt2020nc"),
@@ -602,7 +602,7 @@ class Video(Track):
does it actually call ccextractor.
Even though there is a possibility of more than one c608 box, only one
can actually be extracted. Not only that but it's very possible this
can actually be extracted. It is also very possible this
needs to be done before any decryption as the decryption may destroy
some of the metadata.
+1 -1
View File
@@ -1162,7 +1162,7 @@ def get_debug_logger() -> Optional[DebugLogger]:
def log_event(operation: str, *, level: str = "DEBUG", message: str = "", **kwargs: Any) -> None:
"""Emit a single structured debug-log entry. No-op when debug logging is disabled.
The canonical one-shot logging primitive — replaces the
The canonical one-shot logging primitive. Replaces the
``if dl := get_debug_logger(): dl.log(...)`` guard boilerplate. To add logging to a new
feature, call ``log_event("my_feature_event", message="...", context={...})``.
"""
+4 -4
View File
@@ -59,7 +59,7 @@ def measure_real_bitrate(
Single-file tracks are measured exactly. Segmented tracks probe up to
``samples`` segments spread across the track and extrapolate; byte-range
segments need no request. Returns bits/sec, or ``None`` if it cannot be
measured. Never raises — a probe failure must not abort a download.
measured. Never raises; a probe failure must not abort a download.
"""
from unshackle.core.tracks.track import Track
@@ -74,7 +74,7 @@ def measure_real_bitrate(
# Descriptor.URL: a single file. Some services parse a DASH
# manifest then collapse each representation to its single BaseURL and
# flip the descriptor to URL, leaving the manifest (and its duration) in
# track.data — recover the duration from there, else probe the file.
# track.data: recover the duration from there, else probe the file.
segments = extract_url(track, session, log=log)
if not segments:
log.debug(f"{track.id}: cannot measure real bitrate (no known duration)")
@@ -130,7 +130,7 @@ def apply_real_bitrates(
declared-bitrate tracks per group are probed, in parallel. Each group is then
extended downward: while the lowest probed bitrate in a group sits below the
next unprobed track's declared bitrate (so that track could outrank a probed
one), the next track is probed too — until the probed set is safely above the
one), the next track is probed too, until the probed set is safely above the
rest. Unprobed tracks keep their manifest-declared bitrate.
"""
groups: defaultdict[Hashable, list["Track"]] = defaultdict(list)
@@ -182,7 +182,7 @@ def dedupe(segments: list[Segment]) -> list[Segment]:
Collapse segments that address the same bytes so each object is measured once.
Manifests sometimes wrap a single file in several segment entries sharing one
URL — with no byte range (a ``SegmentTemplate`` whose media pattern has no
URL, with no byte range (a ``SegmentTemplate`` whose media pattern has no
``$Number$``) or with the same range. Each resolves to the whole file, so
counting them all would multiply the size by the segment count. Segments
sharing the same ``(url, byte_range)`` are merged into one entry whose duration
+3 -3
View File
@@ -97,7 +97,7 @@ def lookup_session(source: Optional[requests.Session]) -> requests.Session:
Build a plain, retry-free requests session for IP geolocation.
Geolocation needs no TLS fingerprinting, so we skip the impersonated rnet
session and the base session's urllib3 retry loop — both retry 429 internally,
session and the base session's urllib3 retry loop. Both retry 429 internally,
which hides the response and defeats fast provider handover. With a bare session
a 429 comes straight back so we can move to the next provider immediately. Only
the proxy is carried over so proxied lookups still report the proxy's exit IP.
@@ -139,7 +139,7 @@ def fetch_ipinfo(session: requests.Session) -> Optional[dict]:
def fetch_ip_api_in(session: requests.Session) -> Optional[dict]:
"""ip-api.in has no /me endpoint — resolve IP via ipify first, then look it up."""
"""ip-api.in has no /me endpoint, so resolve IP via ipify first, then look it up."""
ip_resp = session.get("https://api.ipify.org", timeout=REQUEST_TIMEOUT)
if ip_resp.status_code == 429:
raise RateLimited()
@@ -198,7 +198,7 @@ def get_ip_info(
returned info reflects the proxy's exit IP. Auth headers for ipinfo
are sent per-request; never mutated onto session.headers.
cached: When True, read/write a 24h Cacher-backed entry. Use only for
local IP lookups — never with a proxied session.
local IP lookups, never with a proxied session.
"""
cache = None
if cached: