mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-26 19:05:13 +00:00
docs: apply simplified technical english across docs and docstrings.
This commit is contained in:
@@ -56,10 +56,11 @@ def measure_real_bitrate(
|
||||
leaky-bucket ceiling, not an average). This measures the true bitrate
|
||||
(bits/sec) from real media byte sizes and durations using ``bytes * 8 / sec``.
|
||||
|
||||
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.
|
||||
This function measures a single-file track exactly. For a segmented track it
|
||||
probes a maximum of ``samples`` segments spread across the track and
|
||||
extrapolates. A byte-range segment needs no request. Returns bits/sec, or
|
||||
``None`` when unshackle cannot measure the bitrate. Never raises. A probe
|
||||
failure must not abort a download.
|
||||
"""
|
||||
from unshackle.core.tracks.track import Track
|
||||
|
||||
@@ -125,13 +126,13 @@ def apply_real_bitrates(
|
||||
"""
|
||||
Probe real bitrates and overwrite ``track.bitrate`` for the tracks worth probing.
|
||||
|
||||
Probing every rendition is slow when a service exposes dozens. Tracks are
|
||||
grouped by ``group_key`` (a quality tier), and only the ``per_group`` highest
|
||||
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
|
||||
rest. Unprobed tracks keep their manifest-declared bitrate.
|
||||
Probing every rendition is slow when a service exposes dozens. This function
|
||||
groups tracks by ``group_key`` (a quality tier) and probes only the
|
||||
``per_group`` highest declared-bitrate tracks of each group, in parallel. It
|
||||
then extends each group 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), it probes the next track too, until the probed set is
|
||||
safely above the rest. Unprobed tracks keep their manifest-declared bitrate.
|
||||
"""
|
||||
groups: defaultdict[Hashable, list["Track"]] = defaultdict(list)
|
||||
for track in tracks:
|
||||
@@ -179,14 +180,14 @@ def probe_batch(
|
||||
|
||||
def dedupe(segments: list[Segment]) -> list[Segment]:
|
||||
"""
|
||||
Collapse segments that address the same bytes so each object is measured once.
|
||||
Collapse segments that address the same bytes, to measure each object one time only.
|
||||
|
||||
Manifests sometimes wrap a single file in several segment entries sharing one
|
||||
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
|
||||
is the sum they cover. Distinct byte ranges of one file (different offsets) are
|
||||
counting them all would multiply the size by the segment count. This function
|
||||
merges the segments that share the same ``(url, byte_range)`` into one entry
|
||||
whose duration is the sum they cover. Distinct byte ranges of one file (different offsets) are
|
||||
kept individual so their sizes still add up to the full track.
|
||||
"""
|
||||
merged: OrderedDict[tuple[str, Optional[str]], Segment] = OrderedDict()
|
||||
@@ -211,7 +212,7 @@ def pick_samples(segments: list[Segment], samples: int) -> list[Segment]:
|
||||
|
||||
|
||||
def probe_size(segment: Segment, session: Union[Session, RnetSession]) -> Optional[int]:
|
||||
"""Return a segment's byte size via HEAD, falling back to a ranged GET. Validates status."""
|
||||
"""Return a segment's byte size with a HEAD request, falling back to a ranged GET. Validates status."""
|
||||
try:
|
||||
res = session.head(segment.url, allow_redirects=True, timeout=PROBE_TIMEOUT)
|
||||
if getattr(res, "status_code", 0) in (200, 206):
|
||||
@@ -257,10 +258,10 @@ def uniform_segments(
|
||||
total_duration: Optional[float],
|
||||
) -> list[Segment]:
|
||||
"""
|
||||
Build Segments giving each an equal share of the total duration.
|
||||
Assemble Segments giving each an equal share of the total duration.
|
||||
|
||||
Used for DASH: ``DASH.get_period_segments`` returns timeline *start times*
|
||||
rather than per-segment durations, so they cannot be trusted. Segment lengths
|
||||
rather than per-segment durations, so unshackle cannot trust them. Segment lengths
|
||||
are near-uniform in practice, so the track duration (from
|
||||
``mediaPresentationDuration``) split evenly is both correct and timeline-safe.
|
||||
"""
|
||||
@@ -384,10 +385,11 @@ def ffprobe_duration(url: str, session: Union[Session, RnetSession], *, log: log
|
||||
"""
|
||||
Read a single-file track's duration (seconds) without a manifest.
|
||||
|
||||
The bundled ffprobe segfaults on network input, so the file's ``moov`` box is
|
||||
fetched over HTTP with the session (keeping the service's proxy/headers) and
|
||||
piped to ffprobe as local bytes. The head of the file is tried first (VOD is
|
||||
usually faststart), then the tail as a fallback for moov-at-end files.
|
||||
The bundled FFprobe segfaults on network input, so unshackle fetches the
|
||||
file's ``moov`` box over HTTP with the HTTP session (keeping the service's
|
||||
proxy/headers) and pipes it to FFprobe as local bytes. This function tries the
|
||||
head of the file first (VOD is usually faststart), then the tail as a fallback
|
||||
for moov-at-end files.
|
||||
"""
|
||||
head = ranged_get(url, session, f"bytes=0-{MOOV_PROBE_BYTES - 1}")
|
||||
duration = probe_bytes_duration(head, log)
|
||||
@@ -414,7 +416,7 @@ def ranged_get(url: str, session: Union[Session, RnetSession], byte_range: str)
|
||||
|
||||
|
||||
def probe_bytes_duration(data: Optional[bytes], log: logging.Logger) -> Optional[float]:
|
||||
"""Pipe media bytes to ffprobe and return the format/stream duration in seconds."""
|
||||
"""Pipe media bytes to FFprobe and return the container or track duration in seconds."""
|
||||
if not data:
|
||||
return None
|
||||
ffprobe_bin = str(FFProbe) if FFProbe else "ffprobe"
|
||||
|
||||
@@ -187,8 +187,8 @@ class SeasonRange(click.ParamType):
|
||||
def token_sides(self, match: re.Match) -> tuple[int, Optional[int], Optional[int]]:
|
||||
"""Read one side of a token as (season, episode, part), episode/part None when absent.
|
||||
|
||||
A music disc x track token shares this key space, disc reading as the season and
|
||||
track as the episode. An omitted disc is disc 1, not every disc: a bare number is
|
||||
A music disc x track token shares this (season, episode, part) space, disc reading
|
||||
as the season and track as the episode. An omitted disc is disc 1, not every disc: a bare number is
|
||||
the number the tracklist shows for a single-disc release, and widening it would
|
||||
silently add tracks on a multi-disc release.
|
||||
"""
|
||||
@@ -207,16 +207,17 @@ class SeasonRange(click.ParamType):
|
||||
"""
|
||||
Parse multiple tokens or ranged tokens as '{s}x{e}' strings.
|
||||
|
||||
An episode split into separately playable parts is addressed as '{s}x{e}.{p}'.
|
||||
A part range must stay inside one episode, since how many parts an episode has
|
||||
is not knowable here. A part-qualified exclusion cannot be removed from the
|
||||
computed keys (they are base keys), so it becomes a '!' key resolved at match time.
|
||||
You address an episode split into separately playable parts as '{s}x{e}.{p}'.
|
||||
A part range must stay inside one episode, because how many parts an episode has
|
||||
is not knowable here. unshackle cannot remove a part-qualified exclusion from the
|
||||
computed keys, because those are base keys. The exclusion becomes a '!' entry that
|
||||
unshackle applies later, when it matches an episode to the wanted keys.
|
||||
|
||||
Dated content is addressed by ISO air date. A date range uses ':' only, because
|
||||
You address an episode by its ISO air date. A date range uses ':' only, because
|
||||
a date's own '-' separators are not a range separator.
|
||||
|
||||
A music release uses the same keys, its disc reading as the season and its track
|
||||
as the episode. A track is addressed as '{d}x{t}', or by its number alone, which
|
||||
as the episode. You address a track as '{d}x{t}', or by its number alone, which
|
||||
is a track on disc 1.
|
||||
|
||||
Supports exclusioning by putting a `-` before the token.
|
||||
@@ -393,10 +394,10 @@ class AudioCodecList(click.ParamType):
|
||||
|
||||
class MultipleChoice(click.Choice):
|
||||
"""
|
||||
The multiple choice type allows multiple values to be checked against
|
||||
a fixed set of supported values.
|
||||
The multiple choice type takes several values. Each value must be in a fixed
|
||||
set of permitted values.
|
||||
|
||||
It internally uses and is based off of click.Choice.
|
||||
It internally uses and extends click.Choice.
|
||||
"""
|
||||
|
||||
name = "multiple_choice"
|
||||
@@ -428,8 +429,8 @@ class MultipleChoice(click.Choice):
|
||||
|
||||
Parameters:
|
||||
ctx: Invocation context for this command.
|
||||
param: The parameter that is requesting completion.
|
||||
incomplete: Value being completed. May be empty.
|
||||
param: The parameter that requests completion.
|
||||
incomplete: The value to complete. Can be empty.
|
||||
"""
|
||||
incomplete = incomplete.rsplit(",")[-1]
|
||||
return super(self).shell_complete(ctx, param, incomplete)
|
||||
|
||||
@@ -35,7 +35,7 @@ def extract_rpu(
|
||||
status: Optional[str] = "Extracting DV RPU...",
|
||||
label: str = "dovi_tool extract-rpu",
|
||||
) -> bytes:
|
||||
"""Extract DV RPU NALs from a raw HEVC stream. `mode=None` skips the -m flag (untouched)."""
|
||||
"""Extract DV RPU NALs from a raw HEVC bitstream. `mode=None` skips the -m flag (untouched)."""
|
||||
tool = require_dovi_tool()
|
||||
args: list = [tool]
|
||||
if mode is not None:
|
||||
@@ -52,7 +52,7 @@ def inject_rpu(
|
||||
status: Optional[str] = "Re-injecting DV RPU...",
|
||||
label: str = "dovi_tool inject-rpu",
|
||||
) -> bytes:
|
||||
"""Inject a DV RPU back into a raw HEVC stream, producing DV-signaled output."""
|
||||
"""Inject a DV RPU back into a raw HEVC bitstream, producing DV-signaled output."""
|
||||
tool = require_dovi_tool()
|
||||
return run_step(
|
||||
[tool, "inject-rpu", "-i", source, "--rpu-in", rpu, "-o", output],
|
||||
@@ -106,7 +106,7 @@ def generate_from_hdr10plus(
|
||||
status: Optional[str] = "Generating DV RPU from HDR10+ metadata...",
|
||||
label: str = "dovi_tool generate",
|
||||
) -> bytes:
|
||||
"""Build a DV RPU from extracted HDR10+ metadata + an extra JSON descriptor."""
|
||||
"""Assemble a DV RPU from extracted HDR10+ metadata + an extra JSON descriptor."""
|
||||
tool = require_dovi_tool()
|
||||
return run_step(
|
||||
[tool, "generate", "-j", extra_json, "--hdr10plus-json", hdr10plus_json, "-o", output],
|
||||
@@ -117,7 +117,7 @@ def generate_from_hdr10plus(
|
||||
|
||||
|
||||
def extract_rpu_with_fallback(source: Path, output: Path, *, label: str = "dovi_tool extract-rpu") -> bytes:
|
||||
"""Try `-m 3` first; on MAX_PQ_LUMINANCE error, retry untouched (no -m). Returns stderr.
|
||||
"""Try `-m 3` first. On a MAX_PQ_LUMINANCE error, retry untouched (no -m). Returns stderr.
|
||||
|
||||
Used when the caller wants automatic normalization but cannot abort if the source
|
||||
rejects mode-3 conversion.
|
||||
|
||||
@@ -85,7 +85,7 @@ def get_local_storage_data(profile_path: Path, hosts: List[str], tmp_dir_path: P
|
||||
def get_firefox_cookies(service_settings: dict) -> Optional[CookieJar]:
|
||||
"""
|
||||
Extracts cookies and optionally localStorage from Firefox based on provided host patterns.
|
||||
Implements security hardening and data consistency (WAL support) as per PR review.
|
||||
Implements security hardening and data consistency (it can copy the WAL log) as per PR review.
|
||||
"""
|
||||
raw_hosts = service_settings.get("hosts", [])
|
||||
# Filter empty or dangerously short hosts to prevent full store dumps (Finding #3)
|
||||
|
||||
@@ -23,7 +23,7 @@ log = logging.getLogger("ip_info")
|
||||
|
||||
|
||||
class RateLimited(Exception):
|
||||
"""Raised by a provider fetcher when the upstream returns 429."""
|
||||
"""Raised by a geolocation API fetcher when the upstream returns 429."""
|
||||
|
||||
|
||||
def normalize(
|
||||
@@ -37,7 +37,7 @@ def normalize(
|
||||
as_name: str = "",
|
||||
continent_code: str = "",
|
||||
) -> Optional[dict]:
|
||||
"""Build the canonical IP-info dict, or None if no country code is present."""
|
||||
"""Assemble the canonical IP-info dict, or None if no country code is present."""
|
||||
code = country_code.strip()
|
||||
if not code:
|
||||
return None
|
||||
@@ -94,13 +94,14 @@ def parse_ip_api_in(data: dict) -> Optional[dict]:
|
||||
|
||||
def lookup_session(source: Optional[requests.Session]) -> requests.Session:
|
||||
"""
|
||||
Build a plain, retry-free requests session for IP geolocation.
|
||||
Assemble a plain, retry-free `requests` HTTP 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,
|
||||
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.
|
||||
Geolocation needs no TLS fingerprinting, so we skip the impersonated rnet HTTP
|
||||
session, and the urllib3 retry loop of the base HTTP session. Both retry 429
|
||||
internally, which hides the response and defeats fast handover to the next
|
||||
geolocation API. With a bare HTTP session a 429 comes straight back, so we can
|
||||
move to the next API immediately. This function carries over the proxy only, so
|
||||
proxied lookups still report the proxy's exit IP.
|
||||
"""
|
||||
sess = requests.Session()
|
||||
proxies = getattr(source, "proxies", None)
|
||||
@@ -139,7 +140,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, so resolve IP via ipify first, then look it up."""
|
||||
"""ip-api.in has no /me endpoint, so get the IP from 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()
|
||||
@@ -185,20 +186,21 @@ def get_ip_info(
|
||||
cached: bool = False,
|
||||
) -> Optional[dict]:
|
||||
"""
|
||||
Look up IP/geolocation info via ipinfo.io (Lite when `ipinfo_api_key` configured)
|
||||
Look up IP/geolocation info through ipinfo.io (Lite when `ipinfo_api_key` configured)
|
||||
with fallback to ip-api.in.
|
||||
|
||||
Live lookups return a dict with `ip`, `country` (lowercase ISO2), `country_code`
|
||||
(uppercase ISO2), `region`, `city`, `org`, `asn`, `as_name`, `continent_code` and
|
||||
`_provider`. Cached lookups return only `country`/`country_code` (see GEO_CACHE_KEYS).
|
||||
Returns None if every provider fails.
|
||||
Returns None if every geolocation API fails.
|
||||
|
||||
Args:
|
||||
session: Optional requests session. If a proxied session is passed, the
|
||||
returned info reflects the proxy's exit IP. Auth headers for ipinfo
|
||||
are sent per-request; never mutated onto session.headers.
|
||||
session: Optional `requests` HTTP session. If you pass a proxied session,
|
||||
the returned info reflects the proxy's exit IP. unshackle sends the
|
||||
ipinfo auth headers per-request, and never mutates them 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 HTTP session.
|
||||
"""
|
||||
cache = None
|
||||
if cached:
|
||||
|
||||
@@ -19,8 +19,8 @@ def evaluate_language_tag(
|
||||
) -> str:
|
||||
"""Evaluate language tag rules against selected tracks.
|
||||
|
||||
Rules are evaluated in order; the first matching rule's tag is returned.
|
||||
Returns empty string if no rules match.
|
||||
This function evaluates the rules in order. It returns the tag of the first rule
|
||||
that matches, or an empty string if no rule matches.
|
||||
|
||||
Args:
|
||||
rules: List of rule dicts from config, each with conditions and a ``tag``.
|
||||
@@ -28,7 +28,7 @@ def evaluate_language_tag(
|
||||
subtitle_languages: Languages of the selected subtitle tracks.
|
||||
|
||||
Returns:
|
||||
The tag string from the first matching rule, or ``""`` if none match.
|
||||
The tag string from the first rule that matches, or ``""`` if none match.
|
||||
"""
|
||||
for rule in rules:
|
||||
tag = rule.get("tag")
|
||||
@@ -48,7 +48,7 @@ def rule_matches(
|
||||
audio_languages: Sequence[Language],
|
||||
subtitle_languages: Sequence[Language],
|
||||
) -> bool:
|
||||
"""Check if all conditions in a rule are satisfied."""
|
||||
"""Return True when every condition in the rule matches the tracks."""
|
||||
has_condition = False
|
||||
|
||||
audio_lang = rule.get("audio")
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""Run user-defined scripts after a download completes.
|
||||
"""Operate user-defined scripts after a download completes.
|
||||
|
||||
A command is tokenized once, then variables are substituted into the resulting argv
|
||||
tokens and the process is spawned with ``shell=False``. Substituting after tokenizing
|
||||
unshackle tokenizes a command one time, then substitutes the variables into the
|
||||
resulting argv tokens, then spawns the process with ``shell=False``. Substituting after tokenizing
|
||||
is what makes a title like ``Bob"; rm -rf ~`` harmless: a value can never become a new
|
||||
token or a shell operator. The cost is that the command has no shell features and no
|
||||
interpreter lookup, so users name the interpreter themselves (``python upload.py``).
|
||||
@@ -37,7 +37,7 @@ _warned_entries: set[str] = set()
|
||||
|
||||
|
||||
def tokenize(command: str) -> list[str]:
|
||||
"""Split a command string into argv tokens, before any variable is substituted."""
|
||||
"""Split a command string into argv tokens, before unshackle substitutes any variable."""
|
||||
if os.name == "nt":
|
||||
|
||||
def unquote(token: str) -> str:
|
||||
@@ -51,7 +51,7 @@ def tokenize(command: str) -> list[str]:
|
||||
|
||||
|
||||
def substitute(tokens: Sequence[str], context: dict[str, str]) -> list[str]:
|
||||
"""Replace every ``{variable}`` inside each token; unknown or empty ones become ''."""
|
||||
"""Replace every ``{variable}`` inside each token. Unknown or empty ones become ''."""
|
||||
unknown: set[str] = set()
|
||||
|
||||
def replace(match: re.Match[str]) -> str:
|
||||
@@ -92,13 +92,13 @@ def build_context(
|
||||
ids: Optional[dict[str, Any]] = None,
|
||||
error: str = "",
|
||||
) -> dict[str, str]:
|
||||
"""Build the variable set for one output file.
|
||||
"""Assemble the variable set for one output file.
|
||||
|
||||
Metadata comes from the same naming context that produced the file's name, so
|
||||
``{quality}`` and ``{hdr}`` always describe *this* file. That is what lets
|
||||
``-q 1080,2160 -r HDR10,SDR`` label its four outputs correctly. Season and episode
|
||||
are handed over as plain numbers rather than the filename's ``S01E05`` form: the
|
||||
spacer and padding belong to the filename template, not to the data.
|
||||
``{quality}`` and ``{hdr}`` always give the values of *this* file. That is what lets
|
||||
``-q 1080,2160 -r HDR10,SDR`` label its four outputs correctly. unshackle gives the
|
||||
season and the episode as plain numbers rather than in the filename's ``S01E05``
|
||||
form: the spacer and padding belong to the filename template, not to the data.
|
||||
"""
|
||||
context: dict[str, str] = {}
|
||||
|
||||
@@ -152,7 +152,7 @@ def season_context(context: dict[str, str], folder: Path) -> dict[str, str]:
|
||||
|
||||
|
||||
def _entries(event: str, mode: str, overrides: Sequence[str] = ()) -> Iterator[str]:
|
||||
"""Commands configured for this event and mode; --postscript replaces the config list."""
|
||||
"""Commands configured for this event and mode. --postscript replaces the config list."""
|
||||
if overrides:
|
||||
if event == "success" and mode == "file":
|
||||
yield from overrides
|
||||
|
||||
@@ -20,7 +20,7 @@ SENSITIVE_QUERY_PARAM_RE = re.compile(r"(?i)\b(password|passwd|pwd|token|api_key
|
||||
def redact_text(text: Optional[str], secrets: Iterable[str] = ()) -> Optional[str]:
|
||||
"""
|
||||
Mask URL userinfo, secret-bearing query parameters, and any known secret
|
||||
strings inside a free-text value before it is logged or serialized.
|
||||
strings inside a free-text value before unshackle logs or serializes it.
|
||||
"""
|
||||
if not isinstance(text, str) or not text:
|
||||
return text
|
||||
@@ -33,7 +33,7 @@ def redact_text(text: Optional[str], secrets: Iterable[str] = ()) -> Optional[st
|
||||
|
||||
|
||||
def safe_display_url(url: str) -> str:
|
||||
"""Rebuild a URL from its scheme/host/port/path only, so userinfo can never be logged."""
|
||||
"""Rebuild a URL from its scheme/host/port/path only, so unshackle can never log the userinfo."""
|
||||
parts = urlsplit(url)
|
||||
netloc = parts.hostname or ""
|
||||
if parts.port:
|
||||
@@ -42,7 +42,7 @@ def safe_display_url(url: str) -> str:
|
||||
|
||||
|
||||
def path_bases() -> list[tuple[str, str]]:
|
||||
"""Local base directories to strip from logged paths, longest-first.
|
||||
"""Local base directories to remove from logged paths, longest-first.
|
||||
|
||||
Anchors everything left of the unshackle install/root (and the venv / home dir) so an
|
||||
absolute path like ``/home/me/Projects/unshackle-live/temp`` logs as ``<unshackle>/temp``,
|
||||
@@ -90,7 +90,7 @@ def path_redaction_enabled() -> bool:
|
||||
def redact_path(text: Optional[str]) -> Optional[str]:
|
||||
"""Replace local base-directory prefixes (install root, venv, home) in ``text`` with tokens.
|
||||
|
||||
Idempotent and cheap; only touches strings that actually contain a known base dir, so URLs
|
||||
Idempotent and cheap. It touches only the strings that contain a known base dir, so URLs
|
||||
and relative paths pass through unchanged. Disabled by ``config.redact_paths: false``.
|
||||
"""
|
||||
if not isinstance(text, str) or not text or not path_redaction_enabled():
|
||||
@@ -121,7 +121,7 @@ def collapse_url(match: "re.Match[str]") -> str:
|
||||
def redact_url(text: Optional[str]) -> Optional[str]:
|
||||
"""Collapse every http(s) URL in ``text`` to ``redacted[.ext]``.
|
||||
|
||||
Hides content/CDN/manifest/segment/api locations (host + path + query) from shareable debug
|
||||
Hides media/CDN/manifest/segment/api locations (host + path + query) from shareable debug
|
||||
logs while keeping the file extension so the manifest/segment type stays visible
|
||||
(e.g. ``redacted.mpd``). Non-URL strings pass through unchanged.
|
||||
"""
|
||||
|
||||
@@ -31,16 +31,16 @@ class Selector:
|
||||
collapse_on_start: bool = False,
|
||||
):
|
||||
"""
|
||||
Initialize the Selector.
|
||||
Initialise the Selector.
|
||||
|
||||
Args:
|
||||
options: List of strings to select from.
|
||||
cursor_style: Rich style for the highlighted cursor item.
|
||||
text_style: Rich style for normal items.
|
||||
page_size: Number of items to show per page.
|
||||
minimal_count: Minimum number of items that must be selected.
|
||||
minimal_count: Minimum number of items you must select.
|
||||
dependencies: Dictionary mapping parent index to list of child indices.
|
||||
collapse_on_start: If True, child items are hidden initially.
|
||||
collapse_on_start: If True, the Selector hides child items initially.
|
||||
"""
|
||||
self.options = options
|
||||
self.cursor_style = cursor_style
|
||||
@@ -219,7 +219,7 @@ class Selector:
|
||||
def toggle_expand_all(self):
|
||||
"""
|
||||
Toggles expansion state of ALL headers.
|
||||
If all are expanded -> Collapse all.
|
||||
If every header shows its children -> Collapse all.
|
||||
Otherwise -> Expand all.
|
||||
"""
|
||||
if not self.dependencies:
|
||||
@@ -242,7 +242,7 @@ class Selector:
|
||||
def get_input_windows(self):
|
||||
"""
|
||||
Captures and parses keyboard input on Windows systems using msvcrt.
|
||||
Returns command strings like 'UP', 'DOWN', 'ENTER', etc.
|
||||
Returns command strings such as 'UP', 'DOWN', or 'ENTER'.
|
||||
"""
|
||||
key = msvcrt.getch()
|
||||
# Ctrl+C (0x03) or ESC (0x1b)
|
||||
@@ -293,7 +293,7 @@ class Selector:
|
||||
def get_input_unix(self):
|
||||
"""
|
||||
Captures and parses keyboard input on Unix/Linux systems using click.getchar().
|
||||
Returns command strings like 'UP', 'DOWN', 'ENTER', etc.
|
||||
Returns command strings such as 'UP', 'DOWN', or 'ENTER'.
|
||||
"""
|
||||
char = click.getchar()
|
||||
# Ctrl+C
|
||||
@@ -406,9 +406,9 @@ def select_multiple(
|
||||
options: List of options to display.
|
||||
minimal_count: Minimum number of selections required.
|
||||
page_size: Number of items per page.
|
||||
return_indices: If True, returns indices; otherwise returns the option strings.
|
||||
cursor_style: Style color for the cursor.
|
||||
collapse_on_start: If True, child items are hidden initially.
|
||||
return_indices: If True, returns indices. If False, returns the option strings.
|
||||
cursor_style: Style colour for the cursor.
|
||||
collapse_on_start: If True, the Selector hides child items initially.
|
||||
"""
|
||||
selector = Selector(
|
||||
options=options,
|
||||
|
||||
@@ -8,9 +8,9 @@ class SSLCiphers(HTTPAdapter):
|
||||
"""
|
||||
Custom HTTP Adapter to change the TLS Cipher set and security requirements.
|
||||
|
||||
Security Level may optionally be provided. A level above 0 must be used at all times.
|
||||
A list of Security Levels and their security is listed below. Usually 2 is used by default.
|
||||
Do not set the Security level via @SECLEVEL in the cipher list.
|
||||
You can optionally give a Security Level. Always use a level above 0. The list of
|
||||
Security Levels and their security is below. Usually the default is 2.
|
||||
Do not set the Security level with @SECLEVEL in the cipher list.
|
||||
|
||||
Level 0:
|
||||
Everything is permitted. This retains compatibility with previous versions of OpenSSL.
|
||||
|
||||
@@ -17,10 +17,10 @@ def log_tool_run(
|
||||
duration_ms: Optional[float] = None,
|
||||
**context: object,
|
||||
) -> None:
|
||||
"""Emit a structured ``tool_run`` debug-log entry for an external tool invocation.
|
||||
"""Send a structured ``tool_run`` debug-log entry for an external tool invocation.
|
||||
|
||||
Central helper so every binary call (ffmpeg, mkvpropedit, dovi_tool, etc.) logs the
|
||||
same shape. No-op when debug logging is disabled.
|
||||
Central helper so every binary call (FFmpeg, mkvpropedit, dovi_tool, and the other
|
||||
tools) logs the same shape. No-op when debug logging is off.
|
||||
"""
|
||||
dl = get_debug_logger()
|
||||
if not dl:
|
||||
@@ -41,7 +41,7 @@ def log_tool_run(
|
||||
|
||||
|
||||
def ffprobe(uri: Union[bytes, Path]) -> dict:
|
||||
"""Use ffprobe on the provided data to get stream information."""
|
||||
"""Use FFprobe on the provided data to get its track information (``-show_streams``)."""
|
||||
if not binaries.FFProbe:
|
||||
raise EnvironmentError('FFProbe executable "ffprobe" not found but is required.')
|
||||
|
||||
@@ -88,10 +88,10 @@ def run_step(
|
||||
output: Optional[Path] = None,
|
||||
label: str = "subprocess step",
|
||||
) -> bytes:
|
||||
"""Run a CLI step that writes to `output` (when provided). Returns stderr bytes.
|
||||
"""Operate a CLI step that writes to `output` (when provided). Returns stderr bytes.
|
||||
|
||||
Raises RuntimeError with the stderr tail when the process exits non-zero, or when
|
||||
`output` is given and does not exist / is empty after the run.
|
||||
you give `output` and it does not exist or is empty after the step.
|
||||
"""
|
||||
if output is not None:
|
||||
output.unlink(missing_ok=True)
|
||||
|
||||
@@ -26,7 +26,8 @@ NUMBER = re.compile(r"\d+(?:\.\d+)?")
|
||||
def evaluate_tag_rules(rules: Any, context: dict[str, Any]) -> Optional[str]:
|
||||
"""Evaluate tag rules against a filename template context.
|
||||
|
||||
Rules are evaluated in order; the first matching rule's tag is returned.
|
||||
unshackle evaluates the rules in order. It returns the tag of the first rule
|
||||
that matches.
|
||||
Conditions are AND-ed, compared case-insensitively, and a list matches if
|
||||
any entry matches. A value may lead with a comparison operator, e.g.
|
||||
">=2160" or "!=DV".
|
||||
@@ -37,7 +38,7 @@ def evaluate_tag_rules(rules: Any, context: dict[str, Any]) -> Optional[str]:
|
||||
context: The already-built filename template context.
|
||||
|
||||
Returns:
|
||||
The tag string from the first matching rule, or ``None`` if none match.
|
||||
The tag string from the first rule that matches, or ``None`` if none match.
|
||||
"""
|
||||
if not isinstance(rules, list):
|
||||
log.warning("tag_rules must be a list of rules, ignoring: %r", rules)
|
||||
@@ -76,19 +77,19 @@ def evaluate_tag_rules(rules: Any, context: dict[str, Any]) -> Optional[str]:
|
||||
|
||||
|
||||
def has_bool(expected: Any) -> bool:
|
||||
"""Check for a YAML boolean, which is an unquoted word the user meant as text."""
|
||||
"""Examine the expected value for a YAML boolean, which is an unquoted word the user meant as text."""
|
||||
values = expected if isinstance(expected, list) else [expected]
|
||||
return any(isinstance(x, bool) for x in values)
|
||||
|
||||
|
||||
def matches(expected: Any, actual: Any) -> bool:
|
||||
"""Check one condition, where a list matches on any entry."""
|
||||
"""Examine one condition, where a list matches if any one entry matches."""
|
||||
values = expected if isinstance(expected, list) else [expected]
|
||||
return any(matches_one(x, actual) for x in values)
|
||||
|
||||
|
||||
def matches_one(expected: Any, actual: Any) -> bool:
|
||||
"""Check a single value, which may carry a leading comparison operator."""
|
||||
"""Examine a single value, which can carry a leading comparison operator."""
|
||||
text = "" if expected is None else str(expected)
|
||||
for op in sorted(OPS, key=len, reverse=True):
|
||||
if text.startswith(op):
|
||||
|
||||
@@ -67,7 +67,7 @@ def apply_tags(path: Path, tags: dict[str, str]) -> None:
|
||||
|
||||
|
||||
def build_tags_from_ids(ids: ExternalIds, kind: str) -> dict[str, str]:
|
||||
"""Build standard MKV tags from external IDs."""
|
||||
"""Assemble standard MKV tags from external IDs."""
|
||||
tags: dict[str, str] = {}
|
||||
if ids.imdb_id:
|
||||
tags["IMDB"] = ids.imdb_id
|
||||
|
||||
@@ -28,7 +28,7 @@ class TemplateFormatter:
|
||||
"""
|
||||
|
||||
def __init__(self, template: str, spacer: str | None = None):
|
||||
"""Initialize the template formatter.
|
||||
"""Initialise the template formatter.
|
||||
|
||||
Args:
|
||||
template: Template string with variables in {variable} format
|
||||
|
||||
@@ -23,14 +23,15 @@ def merge_segmented_webvtt(vtt_raw: str, segment_durations: Optional[list[int]]
|
||||
Timing lines, cue settings and payload are kept verbatim, so inline formatting
|
||||
(span tags, entities, ASS-style overrides) survives untouched.
|
||||
|
||||
No timestamp offset is applied: segments are expected to carry absolute cue
|
||||
times already (same guard as shaka-player and N_m3u8DL-RE; re-offsetting
|
||||
double-shifts such streams). segment_durations/timescale are accepted for
|
||||
call-site compatibility and only matter if offsetting is ever reintroduced.
|
||||
This function applies no timestamp offset: the segments must already carry absolute
|
||||
cue times. This is the same guard as shaka-player and N_m3u8DL-RE, because
|
||||
re-offsetting double-shifts such documents. This function accepts
|
||||
segment_durations/timescale for call-site compatibility. They only matter if
|
||||
someone reintroduces offsetting.
|
||||
|
||||
Unique STYLE/REGION blocks are kept (players that don't support them ignore
|
||||
them); cue identifiers and NOTE blocks are dropped; cues with a malformed
|
||||
timing line are skipped (downstream sanitizers catch worse).
|
||||
This function keeps unique STYLE/REGION blocks (players that cannot read them ignore
|
||||
them). It drops cue identifiers and NOTE blocks. It skips a cue with a malformed
|
||||
timing line (downstream sanitizers catch worse).
|
||||
"""
|
||||
# each kept cue: [start, end, settings, payload, normalized payload for dedupe]
|
||||
cues: list[list[str]] = []
|
||||
|
||||
Reference in New Issue
Block a user