mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-26 19:05:13 +00:00
Merge branch 'dev' into feat/downloader-speed
# Conflicts: # unshackle/core/api/download_manager.py # unshackle/core/downloaders/requests.py # unshackle/core/manifests/dash.py # unshackle/core/session.py # unshackle/core/utils/webvtt.py
This commit is contained in:
@@ -1,92 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Optional
|
||||
|
||||
from unshackle.core.providers._base import ExternalIds
|
||||
|
||||
log = logging.getLogger("ANIMEAPI")
|
||||
|
||||
PLATFORM_MAP: dict[str, str] = {
|
||||
"mal": "myanimelist",
|
||||
"anilist": "anilist",
|
||||
"kitsu": "kitsu",
|
||||
"tmdb": "themoviedb",
|
||||
"trakt": "trakt",
|
||||
"tvdb": "thetvdb",
|
||||
}
|
||||
|
||||
|
||||
def resolve_animeapi(value: str) -> tuple[Optional[str], ExternalIds]:
|
||||
"""Resolve an anime database ID via AnimeAPI to a title and external IDs.
|
||||
|
||||
Accepts formats like 'mal:12345', 'anilist:98765', or just '12345' (defaults to MAL).
|
||||
Returns (anime_title, ExternalIds) with any TMDB/IMDB/TVDB IDs found.
|
||||
"""
|
||||
import animeapi
|
||||
|
||||
platform_str, id_str = _parse_animeapi_value(value)
|
||||
|
||||
platform_enum = _get_platform(platform_str)
|
||||
if platform_enum is None:
|
||||
log.warning("Unknown AnimeAPI platform: %s (supported: %s)", platform_str, ", ".join(PLATFORM_MAP))
|
||||
return None, ExternalIds()
|
||||
|
||||
log.info("Resolving AnimeAPI %s:%s", platform_str, id_str)
|
||||
|
||||
try:
|
||||
with animeapi.AnimeAPI() as api:
|
||||
relation = api.get_anime_relations(id_str, platform_enum)
|
||||
except Exception as exc:
|
||||
log.warning("AnimeAPI lookup failed for %s:%s: %s", platform_str, id_str, exc)
|
||||
return None, ExternalIds()
|
||||
|
||||
title = getattr(relation, "title", None)
|
||||
|
||||
tmdb_id = getattr(relation, "themoviedb", None)
|
||||
tmdb_type = getattr(relation, "themoviedb_type", None)
|
||||
imdb_id = getattr(relation, "imdb", None)
|
||||
tvdb_id = getattr(relation, "thetvdb", None)
|
||||
|
||||
tmdb_kind: Optional[str] = None
|
||||
if tmdb_type is not None:
|
||||
tmdb_kind = tmdb_type.value if hasattr(tmdb_type, "value") else str(tmdb_type).lower()
|
||||
if tmdb_kind not in ("movie", "tv"):
|
||||
tmdb_kind = "tv"
|
||||
|
||||
external_ids = ExternalIds(
|
||||
tmdb_id=int(tmdb_id) if tmdb_id is not None else None,
|
||||
tmdb_kind=tmdb_kind,
|
||||
imdb_id=str(imdb_id) if imdb_id is not None else None,
|
||||
tvdb_id=int(tvdb_id) if tvdb_id is not None else None,
|
||||
)
|
||||
|
||||
log.info(
|
||||
"AnimeAPI resolved: title=%r, tmdb=%s, imdb=%s, tvdb=%s",
|
||||
title,
|
||||
external_ids.tmdb_id,
|
||||
external_ids.imdb_id,
|
||||
external_ids.tvdb_id,
|
||||
)
|
||||
|
||||
return title, external_ids
|
||||
|
||||
|
||||
def _parse_animeapi_value(value: str) -> tuple[str, str]:
|
||||
"""Parse 'platform:id' format. Defaults to 'mal' if no prefix."""
|
||||
if ":" in value:
|
||||
platform, _, id_str = value.partition(":")
|
||||
return platform.lower().strip(), id_str.strip()
|
||||
return "mal", value.strip()
|
||||
|
||||
|
||||
def _get_platform(platform_str: str) -> object | None:
|
||||
"""Map a platform string to an animeapi.Platform enum value."""
|
||||
import animeapi
|
||||
|
||||
canonical = PLATFORM_MAP.get(platform_str)
|
||||
if canonical is None:
|
||||
return None
|
||||
|
||||
platform_name = canonical.upper()
|
||||
return getattr(animeapi.Platform, platform_name, None)
|
||||
@@ -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.
|
||||
@@ -278,28 +278,26 @@ def extract_dash(track: "Track", session: Union[Session, RnetSession]) -> list[S
|
||||
|
||||
data = track.data["dash"]
|
||||
manifest = data["manifest"]
|
||||
rep_id = data.get("representation_id") or data["representation"].get("id")
|
||||
adaptation_set = data["adaptation_set"]
|
||||
representation = data["representation"]
|
||||
rep_id = data.get("representation_id") or representation.get("id")
|
||||
filtered_period_ids = data.get("filtered_period_ids", [])
|
||||
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:
|
||||
matched_rep = matched_as = None
|
||||
for as_ in period.findall("AdaptationSet"):
|
||||
if DASH.is_trick_mode(as_):
|
||||
continue
|
||||
for rep in as_.findall("Representation"):
|
||||
if rep.get("id") == rep_id:
|
||||
matched_rep, matched_as = rep, as_
|
||||
break
|
||||
if matched_rep is not None:
|
||||
break
|
||||
# rep ids are only unique within an AdaptationSet, so resolve like DASH.download_track
|
||||
if period is stored_period:
|
||||
matched_as, matched_rep = adaptation_set, representation
|
||||
else:
|
||||
matched_as, matched_rep = DASH.resolve_representation(period, rep_id, adaptation_set) or (None, None)
|
||||
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,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import re
|
||||
from datetime import date, timedelta
|
||||
from typing import Any, Optional, Union
|
||||
|
||||
import click
|
||||
@@ -176,6 +177,23 @@ class SeasonRange(click.ParamType):
|
||||
MAX_EPISODE = 999
|
||||
MIN_PART = 1
|
||||
MAX_PART = 99
|
||||
MAX_DATE_SPAN = 1000
|
||||
|
||||
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]:
|
||||
"""Expand an ISO date token or ':'-separated date range into ISO day keys."""
|
||||
try:
|
||||
left = date.fromisoformat(match.group("left"))
|
||||
right = date.fromisoformat(match.group("right")) if match.group("right") else left
|
||||
except ValueError:
|
||||
self.fail(f"Invalid date, must be a real YYYY-MM-DD date: {token}")
|
||||
if left > right:
|
||||
self.fail(f"Invalid range, left side date cannot be later than right side date: {token}")
|
||||
span = (right - left).days + 1
|
||||
if span > self.MAX_DATE_SPAN:
|
||||
self.fail(f"Invalid range, a date range cannot span more than {self.MAX_DATE_SPAN} days: {token}")
|
||||
return [(left + timedelta(days=i)).isoformat() for i in range(span)]
|
||||
|
||||
def parse_tokens(self, *tokens: str) -> list[str]:
|
||||
"""
|
||||
@@ -186,6 +204,9 @@ class SeasonRange(click.ParamType):
|
||||
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.
|
||||
|
||||
Dated content is addressed by ISO air date. A date range uses ':' only, because
|
||||
a date's own '-' separators are not a range separator.
|
||||
|
||||
Supports exclusioning by putting a `-` before the token.
|
||||
|
||||
Example:
|
||||
@@ -200,6 +221,10 @@ class SeasonRange(click.ParamType):
|
||||
["1x1.1", "1x1.2", "1x1.3"]
|
||||
>>> sr.parse_tokens("S01E01", "-S01E01.2")
|
||||
["1x1", "!1x1.2"]
|
||||
>>> sr.parse_tokens("2026-08-11")
|
||||
["2026-08-11"]
|
||||
>>> sr.parse_tokens("2026-08-01:2026-08-03", "-2026-08-02")
|
||||
["2026-08-01", "2026-08-03"]
|
||||
"""
|
||||
if len(tokens) == 0:
|
||||
return []
|
||||
@@ -209,6 +234,11 @@ class SeasonRange(click.ParamType):
|
||||
exclude = token.startswith("-")
|
||||
if exclude:
|
||||
token = token[1:]
|
||||
# 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))
|
||||
continue
|
||||
parsed = [
|
||||
re.match(r"^S(?P<season>\d+)(E(?P<episode>\d+)(\.(?P<part>\d+))?)?$", x, re.IGNORECASE)
|
||||
for x in re.split(r"[:-]", token)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -5,20 +5,16 @@ import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
from typing import Optional, Union
|
||||
from xml.sax.saxutils import escape
|
||||
|
||||
from unshackle.core import binaries
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.providers import (
|
||||
ExternalIds,
|
||||
MetadataResult,
|
||||
enrich_ids,
|
||||
fetch_external_ids,
|
||||
fuzzy_match,
|
||||
get_available_providers,
|
||||
get_provider,
|
||||
search_metadata,
|
||||
resolve_by_ids,
|
||||
)
|
||||
from unshackle.core.titles.episode import Episode
|
||||
from unshackle.core.titles.movie import Movie
|
||||
@@ -68,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:
|
||||
@@ -78,6 +74,8 @@ def _build_tags_from_ids(ids: ExternalIds, kind: str) -> dict[str, str]:
|
||||
if ids.tvdb_id:
|
||||
prefix = "movies" if kind == "movie" else "series"
|
||||
tags["TVDB2"] = f"{prefix}/{ids.tvdb_id}"
|
||||
if ids.anilist_id:
|
||||
tags["ANILIST"] = str(ids.anilist_id)
|
||||
return tags
|
||||
|
||||
|
||||
@@ -87,6 +85,8 @@ def tag_file(
|
||||
tmdb_id: Optional[int] = None,
|
||||
imdb_id: Optional[str] = None,
|
||||
tvdb_id: Optional[int] = None,
|
||||
anilist_id: Optional[Union[int, str]] = None,
|
||||
anime: bool = False,
|
||||
) -> None:
|
||||
log.debug("Tagging file %s with title %r", path, title)
|
||||
custom_tags: dict[str, str] = {}
|
||||
@@ -118,56 +118,18 @@ def tag_file(
|
||||
|
||||
if config.tag_imdb_tmdb:
|
||||
try:
|
||||
providers = get_available_providers()
|
||||
if not providers and tvdb_id is None:
|
||||
has_ids = any(value is not None for value in (tmdb_id, imdb_id, tvdb_id, anilist_id))
|
||||
if not get_available_providers() and not has_ids:
|
||||
log.debug("No metadata providers available; skipping tag lookup")
|
||||
apply_tags(path, custom_tags)
|
||||
return
|
||||
|
||||
result: Optional[MetadataResult] = None
|
||||
|
||||
# Direct ID lookup path
|
||||
if imdb_id:
|
||||
imdbapi = get_provider("imdbapi")
|
||||
if imdbapi:
|
||||
result = imdbapi.get_by_id(imdb_id, kind)
|
||||
if not result:
|
||||
# IMDxAPI is off or had no answer; the ID alone still resolves the others
|
||||
result = MetadataResult(title=name, year=year, kind=kind)
|
||||
result.external_ids.imdb_id = imdb_id
|
||||
enrich_ids(result)
|
||||
elif tmdb_id is not None:
|
||||
tmdb = get_provider("tmdb")
|
||||
if tmdb:
|
||||
result = tmdb.get_by_id(tmdb_id, kind)
|
||||
if result:
|
||||
ext = tmdb.get_external_ids(tmdb_id, kind)
|
||||
result.external_ids = ext
|
||||
enrich_ids(result)
|
||||
else:
|
||||
# Search across providers in priority order
|
||||
result = search_metadata(name, year, kind)
|
||||
|
||||
# If we got a TMDB ID from search but not the other IDs, fetch them
|
||||
if (
|
||||
result
|
||||
and result.external_ids.tmdb_id
|
||||
and not (result.external_ids.imdb_id and result.external_ids.tvdb_id)
|
||||
):
|
||||
ext = fetch_external_ids(result.external_ids.tmdb_id, kind)
|
||||
if ext.imdb_id and not result.external_ids.imdb_id:
|
||||
result.external_ids.imdb_id = ext.imdb_id
|
||||
if ext.tvdb_id and not result.external_ids.tvdb_id:
|
||||
result.external_ids.tvdb_id = ext.tvdb_id
|
||||
enrich_ids(result)
|
||||
|
||||
if tvdb_id is not None:
|
||||
if result is None:
|
||||
result = MetadataResult(kind=kind)
|
||||
result.external_ids.tvdb_id = tvdb_id
|
||||
result = resolve_by_ids(
|
||||
tmdb_id, imdb_id, tvdb_id, anilist_id, title=name, year=year, kind=kind, anime=anime
|
||||
)
|
||||
|
||||
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,15 +61,15 @@ 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]:
|
||||
end_ms = _timestamp_ms(end)
|
||||
if prev is not None and timestamp_ms(start) - prev_end_ms <= 1 and normalized == prev[4]:
|
||||
end_ms = timestamp_ms(end)
|
||||
if end_ms > prev_end_ms: # splice: extend only, never shorten the kept cue
|
||||
prev[1] = end
|
||||
prev_end_ms = end_ms
|
||||
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