mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-26 19:05:13 +00:00
refactor(core)!: drop leading underscores from internal definitions
Renames 314 defs and 41 module/class-level constants. Keeps 11 names underscored where the stripped form collides in scope, plus 5.5.0 shims for the three symbols external service repos call.
This commit is contained in:
@@ -261,7 +261,7 @@ def uniform_segments(
|
||||
"""
|
||||
Build Segments giving each an equal share of the total duration.
|
||||
|
||||
Used for DASH: ``DASH._get_period_segments`` returns timeline *start times*
|
||||
Used for DASH: ``DASH.get_period_segments`` returns timeline *start times*
|
||||
rather than per-segment durations, so they cannot be trusted. Segment lengths
|
||||
are near-uniform in practice, so the track duration (from
|
||||
``mediaPresentationDuration``) split evenly is both correct and timeline-safe.
|
||||
@@ -285,7 +285,7 @@ def extract_dash(track: "Track", session: Union[Session, RnetSession]) -> list[S
|
||||
stored_period = data.get("period")
|
||||
track_url = track.url if isinstance(track.url, str) else track.url[0]
|
||||
|
||||
content_periods = [p for p in manifest.findall("Period") if DASH._is_content_period(p, filtered_period_ids)]
|
||||
content_periods = [p for p in manifest.findall("Period") if DASH.is_content_period(p, filtered_period_ids)]
|
||||
|
||||
raw_segments: list[tuple[str, Optional[str]]] = []
|
||||
for period in content_periods:
|
||||
@@ -297,7 +297,7 @@ def extract_dash(track: "Track", session: Union[Session, RnetSession]) -> list[S
|
||||
if matched_rep is None or matched_as is None:
|
||||
continue
|
||||
|
||||
_, period_segments, _, _, _ = DASH._get_period_segments(
|
||||
_, period_segments, _, _, _ = DASH.get_period_segments(
|
||||
period=period,
|
||||
adaptation_set=matched_as,
|
||||
representation=matched_rep,
|
||||
|
||||
@@ -181,7 +181,7 @@ class SeasonRange(click.ParamType):
|
||||
|
||||
DATE_TOKEN = re.compile(r"^(?P<left>\d{4}-\d{2}-\d{2})(:(?P<right>\d{4}-\d{2}-\d{2}))?$")
|
||||
|
||||
def _parse_date_token(self, token: str, match: re.Match) -> list[str]:
|
||||
def parse_date_token(self, token: str, match: re.Match) -> list[str]:
|
||||
"""Expand an ISO date token or ':'-separated date range into ISO day keys."""
|
||||
try:
|
||||
left = date.fromisoformat(match.group("left"))
|
||||
@@ -237,7 +237,7 @@ class SeasonRange(click.ParamType):
|
||||
# dates carry their own '-' separators, so they must be read before the range split
|
||||
date_match = self.DATE_TOKEN.match(token)
|
||||
if date_match:
|
||||
(computed if not exclude else exclusions).extend(self._parse_date_token(token, date_match))
|
||||
(computed if not exclude else exclusions).extend(self.parse_date_token(token, date_match))
|
||||
continue
|
||||
parsed = [
|
||||
re.match(r"^S(?P<season>\d+)(E(?P<episode>\d+)(\.(?P<part>\d+))?)?$", x, re.IGNORECASE)
|
||||
|
||||
@@ -21,7 +21,7 @@ from unshackle.core import binaries
|
||||
from unshackle.core.utils.subprocess import log_tool_run, run_step
|
||||
|
||||
|
||||
def _require_dovi_tool() -> str:
|
||||
def require_dovi_tool() -> str:
|
||||
if not binaries.DoviTool:
|
||||
raise EnvironmentError("dovi_tool executable was not found but is required.")
|
||||
return str(binaries.DoviTool)
|
||||
@@ -36,7 +36,7 @@ def extract_rpu(
|
||||
label: str = "dovi_tool extract-rpu",
|
||||
) -> bytes:
|
||||
"""Extract DV RPU NALs from a raw HEVC stream. `mode=None` skips the -m flag (untouched)."""
|
||||
tool = _require_dovi_tool()
|
||||
tool = require_dovi_tool()
|
||||
args: list = [tool]
|
||||
if mode is not None:
|
||||
args += ["-m", str(mode)]
|
||||
@@ -53,7 +53,7 @@ def inject_rpu(
|
||||
label: str = "dovi_tool inject-rpu",
|
||||
) -> bytes:
|
||||
"""Inject a DV RPU back into a raw HEVC stream, producing DV-signaled output."""
|
||||
tool = _require_dovi_tool()
|
||||
tool = require_dovi_tool()
|
||||
return run_step(
|
||||
[tool, "inject-rpu", "-i", source, "--rpu-in", rpu, "-o", output],
|
||||
status=status,
|
||||
@@ -71,7 +71,7 @@ def editor(
|
||||
label: str = "dovi_tool editor",
|
||||
) -> bytes:
|
||||
"""Apply a JSON edit spec to an RPU file."""
|
||||
tool = _require_dovi_tool()
|
||||
tool = require_dovi_tool()
|
||||
return run_step(
|
||||
[tool, "editor", "-i", source, "-j", json_spec, "-o", output],
|
||||
status=status,
|
||||
@@ -82,7 +82,7 @@ def editor(
|
||||
|
||||
def info_summary(rpu: Path) -> str:
|
||||
"""Return the textual summary (`dovi_tool info -i ... -s`) for an RPU file."""
|
||||
tool = _require_dovi_tool()
|
||||
tool = require_dovi_tool()
|
||||
info_start = time.monotonic()
|
||||
p = subprocess.run(
|
||||
[tool, "info", "-i", str(rpu), "-s"], capture_output=True, text=True, encoding="utf-8", errors="replace"
|
||||
@@ -107,7 +107,7 @@ def generate_from_hdr10plus(
|
||||
label: str = "dovi_tool generate",
|
||||
) -> bytes:
|
||||
"""Build a DV RPU from extracted HDR10+ metadata + an extra JSON descriptor."""
|
||||
tool = _require_dovi_tool()
|
||||
tool = require_dovi_tool()
|
||||
return run_step(
|
||||
[tool, "generate", "-j", extra_json, "--hdr10plus-json", hdr10plus_json, "-o", output],
|
||||
status=status,
|
||||
|
||||
@@ -36,14 +36,14 @@ def evaluate_language_tag(
|
||||
log.warning("Language tag rule missing 'tag' field, skipping: %s", rule)
|
||||
continue
|
||||
|
||||
if _rule_matches(rule, audio_languages, subtitle_languages):
|
||||
if rule_matches(rule, audio_languages, subtitle_languages):
|
||||
log.debug("Language tag rule matched: %s -> %s", rule, tag)
|
||||
return str(tag)
|
||||
|
||||
return ""
|
||||
|
||||
|
||||
def _rule_matches(
|
||||
def rule_matches(
|
||||
rule: dict[str, Any],
|
||||
audio_languages: Sequence[Language],
|
||||
subtitle_languages: Sequence[Language],
|
||||
|
||||
@@ -41,7 +41,7 @@ def safe_display_url(url: str) -> str:
|
||||
return urlunsplit((parts.scheme, netloc, parts.path, "", ""))
|
||||
|
||||
|
||||
def _path_bases() -> list[tuple[str, str]]:
|
||||
def path_bases() -> list[tuple[str, str]]:
|
||||
"""Local base directories to strip from logged paths, longest-first.
|
||||
|
||||
Anchors everything left of the unshackle install/root (and the venv / home dir) so an
|
||||
@@ -52,14 +52,14 @@ def _path_bases() -> list[tuple[str, str]]:
|
||||
try:
|
||||
# redact.py lives at <root>/unshackle/core/utils/redact.py -> parents[3] == project/install root
|
||||
candidates.append((str(Path(__file__).resolve().parents[3]), "<unshackle>"))
|
||||
except Exception:
|
||||
except (OSError, IndexError):
|
||||
pass
|
||||
for raw in (getattr(sys, "prefix", ""), getattr(sys, "base_prefix", "")):
|
||||
if raw:
|
||||
candidates.append((str(Path(raw)), "<venv>"))
|
||||
try:
|
||||
candidates.append((str(Path.home()), "~"))
|
||||
except Exception:
|
||||
except (OSError, RuntimeError):
|
||||
pass
|
||||
|
||||
bases: list[tuple[str, str]] = []
|
||||
@@ -74,10 +74,10 @@ def _path_bases() -> list[tuple[str, str]]:
|
||||
return bases
|
||||
|
||||
|
||||
_PATH_BASES = _path_bases()
|
||||
PATH_BASES = path_bases()
|
||||
|
||||
|
||||
def _path_redaction_enabled() -> bool:
|
||||
def path_redaction_enabled() -> bool:
|
||||
"""Path-prefix redaction is on unless ``config.redact_paths`` is explicitly False."""
|
||||
try:
|
||||
from unshackle.core.config import config # lazy: config doesn't import redact, so no cycle
|
||||
@@ -93,9 +93,9 @@ def redact_path(text: Optional[str]) -> Optional[str]:
|
||||
Idempotent and cheap; only touches strings that actually 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():
|
||||
if not isinstance(text, str) or not text or not path_redaction_enabled():
|
||||
return text
|
||||
for base, token in _PATH_BASES:
|
||||
for base, token in PATH_BASES:
|
||||
if base in text:
|
||||
text = text.replace(base, token)
|
||||
return text
|
||||
@@ -104,16 +104,16 @@ def redact_path(text: Optional[str]) -> Optional[str]:
|
||||
# any http(s) URL embedded in free text (content/manifest/segment/api locations)
|
||||
URL_RE = re.compile(r"https?://[^\s\"'<>\\]+", re.IGNORECASE)
|
||||
# a plausible file extension to preserve (e.g. .mpd, .m3u8, .mp4, .m4s, .vtt)
|
||||
_EXT_RE = re.compile(r"^\.[A-Za-z0-9]{1,5}$")
|
||||
EXT_RE = re.compile(r"^\.[A-Za-z0-9]{1,5}$")
|
||||
|
||||
|
||||
def _collapse_url(match: "re.Match[str]") -> str:
|
||||
def collapse_url(match: "re.Match[str]") -> str:
|
||||
url = match.group(0)
|
||||
try:
|
||||
suffix = Path(urlsplit(url).path).suffix
|
||||
except Exception:
|
||||
suffix = ""
|
||||
if not _EXT_RE.match(suffix):
|
||||
if not EXT_RE.match(suffix):
|
||||
suffix = ""
|
||||
return f"redacted{suffix}"
|
||||
|
||||
@@ -127,7 +127,7 @@ def redact_url(text: Optional[str]) -> Optional[str]:
|
||||
"""
|
||||
if not isinstance(text, str) or not text:
|
||||
return text
|
||||
return URL_RE.sub(_collapse_url, text)
|
||||
return URL_RE.sub(collapse_url, text)
|
||||
|
||||
|
||||
def redact_all(text: Optional[str]) -> Optional[str]:
|
||||
|
||||
@@ -10,7 +10,7 @@ from typing import Any, Callable, Optional
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
_OPS: dict[str, Callable[[Any, Any], bool]] = {
|
||||
OPS: dict[str, Callable[[Any, Any], bool]] = {
|
||||
">=": operator.ge,
|
||||
"<=": operator.le,
|
||||
"!=": operator.ne,
|
||||
@@ -19,8 +19,8 @@ _OPS: dict[str, Callable[[Any, Any], bool]] = {
|
||||
"<": operator.lt,
|
||||
"=": operator.eq,
|
||||
}
|
||||
_ORDERING = (">=", "<=", ">", "<")
|
||||
_NUMBER = re.compile(r"\d+(?:\.\d+)?")
|
||||
ORDERING = (">=", "<=", ">", "<")
|
||||
NUMBER = re.compile(r"\d+(?:\.\d+)?")
|
||||
|
||||
|
||||
def evaluate_tag_rules(rules: Any, context: dict[str, Any]) -> Optional[str]:
|
||||
@@ -56,7 +56,7 @@ def evaluate_tag_rules(rules: Any, context: dict[str, Any]) -> Optional[str]:
|
||||
if not when or not tag:
|
||||
log.warning("Tag rule needs both 'when' conditions and a 'tag', skipping: %s", rule)
|
||||
continue
|
||||
if isinstance(tag, bool) or any(_has_bool(value) for value in when.values()):
|
||||
if isinstance(tag, bool) or any(has_bool(value) for value in when.values()):
|
||||
log.warning("Tag rule has a YAML boolean, quote the value to use it as text, skipping: %s", rule)
|
||||
continue
|
||||
if not isinstance(tag, (str, int, float)):
|
||||
@@ -68,35 +68,35 @@ def evaluate_tag_rules(rules: Any, context: dict[str, Any]) -> Optional[str]:
|
||||
log.warning("Tag rule has unknown 'when' key(s) %s, skipping: %s", ", ".join(sorted(unknown)), rule)
|
||||
continue
|
||||
|
||||
if all(_matches(expected, context[key]) for key, expected in when.items()):
|
||||
if all(matches(expected, context[key]) for key, expected in when.items()):
|
||||
log.debug("Tag rule matched: %s -> %s", rule, tag)
|
||||
return str(tag)
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def _has_bool(expected: Any) -> bool:
|
||||
def has_bool(expected: Any) -> bool:
|
||||
"""Check 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:
|
||||
def matches(expected: Any, actual: Any) -> bool:
|
||||
"""Check one condition, where a list matches on any entry."""
|
||||
values = expected if isinstance(expected, list) else [expected]
|
||||
return any(_matches_one(x, actual) for x in values)
|
||||
return any(matches_one(x, actual) for x in values)
|
||||
|
||||
|
||||
def _matches_one(expected: Any, actual: Any) -> bool:
|
||||
def matches_one(expected: Any, actual: Any) -> bool:
|
||||
"""Check a single value, which may carry a leading comparison operator."""
|
||||
text = "" if expected is None else str(expected)
|
||||
for op in sorted(_OPS, key=len, reverse=True):
|
||||
for op in sorted(OPS, key=len, reverse=True):
|
||||
if text.startswith(op):
|
||||
return _compare(op, text[len(op) :].strip(), actual)
|
||||
return compare(op, text[len(op) :].strip(), actual)
|
||||
return str(actual or "").lower() == text.lower()
|
||||
|
||||
|
||||
def _compare(op: str, operand: str, actual: Any) -> bool:
|
||||
def compare(op: str, operand: str, actual: Any) -> bool:
|
||||
"""Compare against an operand, numerically when the operand is a number."""
|
||||
if not operand:
|
||||
log.warning("Tag rule condition '%s' has no value to compare against, condition failed", op)
|
||||
@@ -105,12 +105,12 @@ def _compare(op: str, operand: str, actual: Any) -> bool:
|
||||
try:
|
||||
wanted = float(operand)
|
||||
except ValueError:
|
||||
if op in _ORDERING:
|
||||
if op in ORDERING:
|
||||
log.warning("Tag rule condition '%s%s' needs a numeric operand, condition failed", op, operand)
|
||||
return False
|
||||
return _OPS[op](str(actual or "").lower(), operand.lower())
|
||||
return OPS[op](str(actual or "").lower(), operand.lower())
|
||||
|
||||
found = _NUMBER.search(str(actual or ""))
|
||||
found = NUMBER.search(str(actual or ""))
|
||||
if not found:
|
||||
return op == "!="
|
||||
return _OPS[op](float(found.group()), wanted)
|
||||
return OPS[op](float(found.group()), wanted)
|
||||
|
||||
@@ -64,7 +64,7 @@ def apply_tags(path: Path, tags: dict[str, str]) -> None:
|
||||
tmp_path.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def _build_tags_from_ids(ids: ExternalIds, kind: str) -> dict[str, str]:
|
||||
def build_tags_from_ids(ids: ExternalIds, kind: str) -> dict[str, str]:
|
||||
"""Build standard MKV tags from external IDs."""
|
||||
tags: dict[str, str] = {}
|
||||
if ids.imdb_id:
|
||||
@@ -129,7 +129,7 @@ def tag_file(
|
||||
)
|
||||
|
||||
if result and result.external_ids:
|
||||
standard_tags = _build_tags_from_ids(result.external_ids, kind)
|
||||
standard_tags = build_tags_from_ids(result.external_ids, kind)
|
||||
except Exception as e:
|
||||
log.warning("Metadata lookup failed, applying custom tags only: %s", e)
|
||||
|
||||
|
||||
@@ -38,9 +38,9 @@ class TemplateFormatter:
|
||||
"""
|
||||
self.template = template
|
||||
self.spacer = spacer or detect_spacer(template)
|
||||
self.variables = self._extract_variables()
|
||||
self.variables = self.extract_variables()
|
||||
|
||||
def _extract_variables(self) -> list[str]:
|
||||
def extract_variables(self) -> list[str]:
|
||||
"""Extract all variables from the template."""
|
||||
pattern = r"\{([^}]+)\}"
|
||||
matches = re.findall(pattern, self.template)
|
||||
@@ -82,7 +82,7 @@ class TemplateFormatter:
|
||||
# Remove the placeholder and consume the adjacent separator on one side
|
||||
# e.g. "{disc?}-{track}" → "{track}" when disc is empty
|
||||
# e.g. "{title}.{edition?}.{quality}" → "{title}.{quality}" when edition is empty
|
||||
def _remove_conditional(m: re.Match) -> str:
|
||||
def remove_conditional(m: re.Match) -> str:
|
||||
s = m.group(0)
|
||||
has_left = s[0] in ".- "
|
||||
has_right = s[-1] in ".- "
|
||||
@@ -94,7 +94,7 @@ class TemplateFormatter:
|
||||
|
||||
result = re.sub(
|
||||
rf"[\.\s\-]?{re.escape(placeholder)}[\.\s\-]?",
|
||||
_remove_conditional,
|
||||
remove_conditional,
|
||||
result,
|
||||
count=1,
|
||||
)
|
||||
|
||||
@@ -2,10 +2,10 @@ import re
|
||||
from typing import Optional
|
||||
|
||||
# Timing line: optional hours, verbatim settings tail.
|
||||
_TIMING = re.compile(r"^((?:\d+:)?\d{2}:\d{2}\.\d{3})[ \t]+-->[ \t]+((?:\d+:)?\d{2}:\d{2}\.\d{3})(.*)$")
|
||||
TIMING = re.compile(r"^((?:\d+:)?\d{2}:\d{2}\.\d{3})[ \t]+-->[ \t]+((?:\d+:)?\d{2}:\d{2}\.\d{3})(.*)$")
|
||||
|
||||
|
||||
def _timestamp_ms(ts: str) -> int:
|
||||
def timestamp_ms(ts: str) -> int:
|
||||
hms, ms = ts.rsplit(".", 1)
|
||||
parts = [int(p) for p in hms.split(":")]
|
||||
while len(parts) < 3:
|
||||
@@ -52,7 +52,7 @@ def merge_segmented_webvtt(vtt_raw: str, segment_durations: Optional[list[int]]
|
||||
if header not in headers: # segments repeat the same block
|
||||
headers.append(header)
|
||||
continue
|
||||
timing = _TIMING.match(lines[timing_i].strip())
|
||||
timing = TIMING.match(lines[timing_i].strip())
|
||||
if not timing:
|
||||
continue
|
||||
start, end, settings = timing.groups()
|
||||
@@ -61,13 +61,13 @@ def merge_segmented_webvtt(vtt_raw: str, segment_durations: Optional[list[int]]
|
||||
continue
|
||||
|
||||
normalized = "\n".join(line.strip() for line in payload)
|
||||
if prev is not None and _timestamp_ms(start) - prev_end_ms <= 1 and normalized == prev[4]:
|
||||
if prev is not None and timestamp_ms(start) - prev_end_ms <= 1 and normalized == prev[4]:
|
||||
prev[1] = end # splice: extend the kept cue, drop the duplicate
|
||||
prev_end_ms = _timestamp_ms(end)
|
||||
prev_end_ms = timestamp_ms(end)
|
||||
continue
|
||||
|
||||
prev = [start, end, settings, "\n".join(payload), normalized]
|
||||
prev_end_ms = _timestamp_ms(end)
|
||||
prev_end_ms = timestamp_ms(end)
|
||||
cues.append(prev)
|
||||
|
||||
blocks = headers + [f"{c[0]} --> {c[1]}{c[2]}\n{c[3]}" for c in cues]
|
||||
|
||||
Reference in New Issue
Block a user