mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-12-04 23:15:07 +00:00
Compare commits
5
Commits
eeec4e1f1b
...
65ceb4ae51
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
65ceb4ae51 | ||
|
|
c8883a5404 | ||
|
|
13d7636d86 | ||
|
|
6ce7b6c4d3 | ||
|
|
798ce95042 |
+20
-2
@@ -6,7 +6,7 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm
|
||||
|
||||
This changelog is automatically generated using [git-cliff](https://git-cliff.org).
|
||||
|
||||
## [3.1.0] - 2026-02-23
|
||||
## [Unreleased]
|
||||
|
||||
### Features
|
||||
|
||||
@@ -15,6 +15,10 @@ This changelog is automatically generated using [git-cliff](https://git-cliff.or
|
||||
- *debug*: Log binary tool versions at session start
|
||||
- *dl*: Add --repack flag to insert REPACK tag in output filenames
|
||||
- *core*: Add TrackRequest system for multi-codec/multi-range support
|
||||
- *dl*: Add --output option to override download directory
|
||||
- *tracks*: Add edition tags to output filenames
|
||||
- *templates*: [**breaking**] Add customizable output filename templates
|
||||
- *templates*: Add configurable language tagging rule engine
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
@@ -25,11 +29,25 @@ This changelog is automatically generated using [git-cliff](https://git-cliff.or
|
||||
- *dl*: Allow selection of audio tracks for 'all' languages in addition to 'best'
|
||||
- *dl*: Overwrite existing files on re-download and use atomic replace
|
||||
- *dl*: Handle cross-device moves when temp and downloads differ
|
||||
- *track*: Fallback to requests downloader from n_m3u8dl_re for unsupported track types
|
||||
- *n_m3u8dl_re*: Disable segment count validation for duration-based DASH
|
||||
- Correct formatting and add missing newlines in selector and EXAMPLE service
|
||||
- *dependencies*: Update pyplayready version to 0.8.3 and adjust dependencies
|
||||
|
||||
### Documentation
|
||||
|
||||
- Update and correct configuration documentation
|
||||
|
||||
### Changes
|
||||
|
||||
- *hybrid*: Replace log.info with console status and add JSONL debug logging
|
||||
- *dl*: Remove legacy multi-fetch loop for unmigrated services
|
||||
- *example*: Migrate EXAMPLE service to track_request pattern
|
||||
- *providers*: Extract metadata providers into modular system
|
||||
|
||||
### Maintenance
|
||||
|
||||
- *changelog*: Update changelog for upcoming release and reorganize sections
|
||||
|
||||
## [3.0.0] - 2026-02-15
|
||||
|
||||
@@ -511,7 +529,7 @@ This changelog is automatically generated using [git-cliff](https://git-cliff.or
|
||||
- Reorganize Planned Features section in README for clarity
|
||||
- Improve track selection logic in dl.py
|
||||
|
||||
[3.1.0]: https://github.com/unshackle-dl/unshackle/compare/3.0.0..3.1.0
|
||||
[unreleased]: https://github.com/unshackle-dl/unshackle/compare/3.0.0..HEAD
|
||||
[3.0.0]: https://github.com/unshackle-dl/unshackle/compare/2.3.0..3.0.0
|
||||
[2.3.0]: https://github.com/unshackle-dl/unshackle/compare/2.2.0..2.3.0
|
||||
[2.2.0]: https://github.com/unshackle-dl/unshackle/compare/2.1.0..2.2.0
|
||||
|
||||
+92
-12
@@ -30,16 +30,102 @@ filenames:
|
||||
|
||||
---
|
||||
|
||||
## scene_naming (bool)
|
||||
## output_template (dict)
|
||||
|
||||
Set scene-style naming for titles. When `true` uses scene naming patterns (e.g., `Prime.Suspect.S07E01...`), when
|
||||
`false` uses a more human-readable style (e.g., `Prime Suspect S07E01 ...`). Default: `true`.
|
||||
Configure custom output filename templates for movies, series, and songs.
|
||||
This is **required** in your `unshackle.yaml` — a warning is shown if not configured.
|
||||
|
||||
Available variables: `{title}`, `{year}`, `{season}`, `{episode}`, `{season_episode}`, `{episode_name}`,
|
||||
`{quality}`, `{resolution}`, `{source}`, `{audio}`, `{audio_channels}`, `{audio_full}`,
|
||||
`{video}`, `{hdr}`, `{hfr}`, `{atmos}`, `{dual}`, `{multi}`, `{tag}`, `{edition}`, `{repack}`,
|
||||
`{lang_tag}`
|
||||
|
||||
Add `?` suffix to make a variable conditional (omitted when empty): `{year?}`, `{hdr?}`, `{repack?}`
|
||||
|
||||
```yaml
|
||||
output_template:
|
||||
# Scene-style (dot-separated)
|
||||
movies: '{title}.{year}.{repack?}.{edition?}.{quality}.{source}.WEB-DL.{dual?}.{multi?}.{audio_full}.{atmos?}.{hdr?}.{hfr?}.{video}-{tag}'
|
||||
series: '{title}.{year?}.{season_episode}.{episode_name?}.{repack?}.{edition?}.{quality}.{source}.WEB-DL.{dual?}.{multi?}.{audio_full}.{atmos?}.{hdr?}.{hfr?}.{video}-{tag}'
|
||||
songs: '{track_number}.{title}.{repack?}.{edition?}.{source?}.WEB-DL.{audio_full}.{atmos?}-{tag}'
|
||||
|
||||
# Plex-friendly (space-separated)
|
||||
# movies: '{title} ({year}) {quality}'
|
||||
# series: '{title} {season_episode} {episode_name?}'
|
||||
# songs: '{track_number}. {title}'
|
||||
```
|
||||
|
||||
Example outputs:
|
||||
- Scene movies: `The.Matrix.1999.1080p.NF.WEB-DL.DDP5.1.H.264-EXAMPLE`
|
||||
- Scene movies (REPACK): `Dune.2021.REPACK.2160p.HBO.WEB-DL.DDP5.1.H.265-EXAMPLE`
|
||||
- Scene series: `Breaking.Bad.2008.S01E01.Pilot.1080p.NF.WEB-DL.DDP5.1.H.264-EXAMPLE`
|
||||
- Plex movies: `The Matrix (1999) 1080p`
|
||||
|
||||
---
|
||||
|
||||
## dash_naming (bool)
|
||||
---
|
||||
|
||||
Use dash-separated naming convention for output files. Default: `false`.
|
||||
## language_tags (dict)
|
||||
|
||||
Automatically adds language-based identifiers (e.g., `DANiSH`, `NORDiC`, `DKsubs`) to output filenames
|
||||
based on audio and subtitle track languages. Use `{lang_tag?}` in your `output_template` to place the tag.
|
||||
|
||||
Rules are evaluated in order; the first matching rule wins. All conditions within a single rule
|
||||
must match (AND logic). If no rules match, `{lang_tag?}` is cleanly removed from the filename.
|
||||
|
||||
### Conditions
|
||||
|
||||
| Condition | Type | Description |
|
||||
|-----------|------|-------------|
|
||||
| `audio` | string | Matches if any selected audio track has this language |
|
||||
| `subs_contain` | string | Matches if any selected subtitle has this language |
|
||||
| `subs_contain_all` | list | Matches if subtitles include ALL listed languages |
|
||||
|
||||
Language matching uses fuzzy matching (e.g., `en` matches `en-US`, `en-GB`).
|
||||
|
||||
### Example: Nordic tagging
|
||||
|
||||
```yaml
|
||||
language_tags:
|
||||
rules:
|
||||
- audio: da
|
||||
tag: DANiSH
|
||||
- audio: sv
|
||||
tag: SWEDiSH
|
||||
- audio: nb
|
||||
tag: NORWEGiAN
|
||||
- audio: en
|
||||
subs_contain_all: [da, sv, nb]
|
||||
tag: NORDiC
|
||||
- audio: en
|
||||
subs_contain: da
|
||||
tag: DKsubs
|
||||
|
||||
output_template:
|
||||
movies: '{title}.{year?}.{lang_tag?}.{quality}.{source}.WEB-DL.{audio_full}.{video}-{tag}'
|
||||
```
|
||||
|
||||
Example outputs:
|
||||
- Danish audio: `Show.S01E01.DANiSH.1080p.NF.WEB-DL.DDP5.1.H.264-TAG`
|
||||
- English audio + multiple Nordic subs: `Show.S01E01.NORDiC.1080p.NF.WEB-DL.DDP5.1.H.264-TAG`
|
||||
- English audio + Danish subs only: `Show.S01E01.DKsubs.1080p.NF.WEB-DL.DDP5.1.H.264-TAG`
|
||||
- No matching languages: `Show.S01E01.1080p.NF.WEB-DL.DDP5.1.H.264-TAG`
|
||||
|
||||
### Example: Other regional tags
|
||||
|
||||
```yaml
|
||||
language_tags:
|
||||
rules:
|
||||
- audio: nl
|
||||
tag: DUTCH
|
||||
- audio: de
|
||||
tag: GERMAN
|
||||
- audio: fr
|
||||
subs_contain: en
|
||||
tag: ENGFR
|
||||
- audio: fr
|
||||
tag: FRENCH
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
@@ -50,16 +136,10 @@ to ASCII equivalents. Default: `false`.
|
||||
|
||||
---
|
||||
|
||||
## series_year (bool)
|
||||
|
||||
Whether to include the series year in series names for episodes and folders. Default: `true`.
|
||||
|
||||
---
|
||||
|
||||
## tag (str)
|
||||
|
||||
Group or Username to postfix to the end of download filenames following a dash.
|
||||
Only applies when `scene_naming` is enabled.
|
||||
Use `{tag}` in your output template to include it.
|
||||
For example, `tag: "J0HN"` will have `-J0HN` at the end of all download filenames.
|
||||
|
||||
---
|
||||
|
||||
+2
-2
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
||||
|
||||
[project]
|
||||
name = "unshackle"
|
||||
version = "3.1.0"
|
||||
version = "4.0.0"
|
||||
description = "Modular Movie, TV, and Music Archival Software."
|
||||
authors = [{ name = "unshackle team" }]
|
||||
requires-python = ">=3.10,<3.13"
|
||||
@@ -56,7 +56,7 @@ dependencies = [
|
||||
"urllib3>=2.6.3,<3",
|
||||
"chardet>=5.2.0,<6",
|
||||
"curl-cffi>=0.7.0b4,<0.14",
|
||||
"pyplayready>=0.6.3,<0.7",
|
||||
"pyplayready>=0.8.3,<0.9",
|
||||
"httpx>=0.28.1,<0.29",
|
||||
"cryptography>=45.0.0,<47",
|
||||
"subby",
|
||||
|
||||
@@ -2399,13 +2399,14 @@ class dl:
|
||||
|
||||
final_dir.mkdir(parents=True, exist_ok=True)
|
||||
final_path = final_dir / f"{final_filename}{muxed_path.suffix}"
|
||||
template_type = "series" if isinstance(title, Episode) else "songs" if isinstance(title, Song) else "movies"
|
||||
sep = config.get_template_separator(template_type)
|
||||
|
||||
if final_path.exists() and audio_codec_suffix and append_audio_codec_suffix:
|
||||
sep = "." if config.scene_naming else " "
|
||||
final_filename = f"{final_filename.rstrip()}{sep}{audio_codec_suffix.name}"
|
||||
final_path = final_dir / f"{final_filename}{muxed_path.suffix}"
|
||||
|
||||
if final_path in used_final_paths:
|
||||
sep = "." if config.scene_naming else " "
|
||||
i = 2
|
||||
while final_path in used_final_paths:
|
||||
final_path = final_dir / f"{final_filename.rstrip()}{sep}{i}{muxed_path.suffix}"
|
||||
|
||||
@@ -1 +1 @@
|
||||
__version__ = "3.1.0"
|
||||
__version__ = "4.0.0"
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
from typing import Any, Optional
|
||||
|
||||
@@ -93,11 +95,27 @@ class Config:
|
||||
self.decrypt_labs_api_key: str = kwargs.get("decrypt_labs_api_key") or ""
|
||||
self.update_checks: bool = kwargs.get("update_checks", True)
|
||||
self.update_check_interval: int = kwargs.get("update_check_interval", 24)
|
||||
self.scene_naming: bool = kwargs.get("scene_naming", True)
|
||||
self.dash_naming: bool = kwargs.get("dash_naming", False)
|
||||
self.series_year: bool = kwargs.get("series_year", True)
|
||||
|
||||
self.language_tags: dict = kwargs.get("language_tags") or {}
|
||||
self.output_template: dict = kwargs.get("output_template") or {}
|
||||
|
||||
if kwargs.get("scene_naming") is not None:
|
||||
raise SystemExit(
|
||||
"ERROR: The 'scene_naming' option has been removed.\n"
|
||||
"Please configure 'output_template' in your unshackle.yaml instead.\n"
|
||||
"See unshackle-example.yaml for examples."
|
||||
)
|
||||
|
||||
if not self.output_template:
|
||||
raise SystemExit(
|
||||
"ERROR: No 'output_template' configured in your unshackle.yaml.\n"
|
||||
"Please add an 'output_template' section with movies, series, and songs templates.\n"
|
||||
"See unshackle-example.yaml for examples."
|
||||
)
|
||||
|
||||
self._validate_output_templates()
|
||||
|
||||
self.unicode_filenames: bool = kwargs.get("unicode_filenames", False)
|
||||
self.insert_episodename_into_filenames: bool = kwargs.get("insert_episodename_into_filenames", True)
|
||||
|
||||
self.title_cache_time: int = kwargs.get("title_cache_time", 1800) # 30 minutes default
|
||||
self.title_cache_max_retention: int = kwargs.get("title_cache_max_retention", 86400) # 24 hours default
|
||||
@@ -106,6 +124,78 @@ class Config:
|
||||
self.debug: bool = kwargs.get("debug", False)
|
||||
self.debug_keys: bool = kwargs.get("debug_keys", False)
|
||||
|
||||
def _validate_output_templates(self) -> None:
|
||||
"""Validate output template configurations and warn about potential issues."""
|
||||
if not self.output_template:
|
||||
return
|
||||
|
||||
valid_variables = {
|
||||
"title",
|
||||
"year",
|
||||
"season",
|
||||
"episode",
|
||||
"season_episode",
|
||||
"episode_name",
|
||||
"quality",
|
||||
"resolution",
|
||||
"source",
|
||||
"tag",
|
||||
"track_number",
|
||||
"artist",
|
||||
"album",
|
||||
"disc",
|
||||
"audio",
|
||||
"audio_channels",
|
||||
"audio_full",
|
||||
"atmos",
|
||||
"dual",
|
||||
"multi",
|
||||
"video",
|
||||
"hdr",
|
||||
"hfr",
|
||||
"edition",
|
||||
"repack",
|
||||
"lang_tag",
|
||||
}
|
||||
|
||||
unsafe_chars = r'[<>:"/\\|?*]'
|
||||
|
||||
for template_type, template_str in self.output_template.items():
|
||||
if not isinstance(template_str, str):
|
||||
warnings.warn(f"Template '{template_type}' must be a string, got {type(template_str).__name__}")
|
||||
continue
|
||||
|
||||
variables = re.findall(r"\{([^}]+)\}", template_str)
|
||||
|
||||
for var in variables:
|
||||
var_clean = var.rstrip("?")
|
||||
if var_clean not in valid_variables:
|
||||
warnings.warn(f"Unknown template variable '{var}' in {template_type} template")
|
||||
|
||||
test_template = re.sub(r"\{[^}]+\}", "TEST", template_str)
|
||||
if re.search(unsafe_chars, test_template):
|
||||
warnings.warn(f"Template '{template_type}' may contain filesystem-unsafe characters")
|
||||
|
||||
if not template_str.strip():
|
||||
warnings.warn(f"Template '{template_type}' is empty")
|
||||
|
||||
def get_template_separator(self, template_type: str = "movies") -> str:
|
||||
"""Get the filename separator for the given template type.
|
||||
|
||||
Analyzes the active template to determine whether it uses dots or spaces
|
||||
between variables. Falls back to dot separator (scene-style) by default.
|
||||
|
||||
Args:
|
||||
template_type: One of "movies", "series", or "songs".
|
||||
"""
|
||||
template = self.output_template[template_type]
|
||||
between_vars = re.findall(r"\}([^{]*)\{", template)
|
||||
separator_text = "".join(between_vars)
|
||||
dot_count = separator_text.count(".")
|
||||
space_count = separator_text.count(" ")
|
||||
|
||||
return " " if space_count > dot_count else "."
|
||||
|
||||
@classmethod
|
||||
def from_yaml(cls, path: Path) -> Config:
|
||||
if not path.exists():
|
||||
|
||||
@@ -9,9 +9,9 @@ from rich.tree import Tree
|
||||
from sortedcontainers import SortedKeyList
|
||||
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.constants import AUDIO_CODEC_MAP, DYNAMIC_RANGE_MAP, VIDEO_CODEC_MAP
|
||||
from unshackle.core.titles.title import Title
|
||||
from unshackle.core.utilities import sanitize_filename
|
||||
from unshackle.core.utils.template_formatter import TemplateFormatter
|
||||
|
||||
|
||||
class Episode(Title):
|
||||
@@ -78,180 +78,60 @@ class Episode(Title):
|
||||
self.year = year
|
||||
self.description = description
|
||||
|
||||
def _build_template_context(self, media_info: MediaInfo, show_service: bool = True) -> dict:
|
||||
"""Build template context dictionary from MediaInfo."""
|
||||
context = self._build_base_template_context(media_info, show_service)
|
||||
context["title"] = self.title.replace("$", "S")
|
||||
context["year"] = self.year or ""
|
||||
context["season"] = f"S{self.season:02}"
|
||||
context["episode"] = f"E{self.number:02}"
|
||||
context["season_episode"] = f"S{self.season:02}E{self.number:02}"
|
||||
context["episode_name"] = self.name or ""
|
||||
return context
|
||||
|
||||
def __str__(self) -> str:
|
||||
return "{title}{year} S{season:02}E{number:02} {name}".format(
|
||||
title=self.title,
|
||||
year=f" {self.year}" if self.year and config.series_year else "",
|
||||
year=f" {self.year}" if self.year else "",
|
||||
season=self.season,
|
||||
number=self.number,
|
||||
name=self.name or "",
|
||||
).strip()
|
||||
|
||||
def get_filename(self, media_info: MediaInfo, folder: bool = False, show_service: bool = True) -> str:
|
||||
primary_video_track = next(iter(media_info.video_tracks), None)
|
||||
primary_audio_track = None
|
||||
if media_info.audio_tracks:
|
||||
sorted_audio = sorted(
|
||||
media_info.audio_tracks,
|
||||
key=lambda x: (
|
||||
float(x.bit_rate) if x.bit_rate else 0,
|
||||
bool(x.format_additionalfeatures and "JOC" in x.format_additionalfeatures),
|
||||
),
|
||||
reverse=True,
|
||||
)
|
||||
primary_audio_track = sorted_audio[0]
|
||||
unique_audio_languages = len({x.language.split("-")[0] for x in media_info.audio_tracks if x.language})
|
||||
|
||||
def _get_resolution_token(track: Any) -> str:
|
||||
if not track or not getattr(track, "height", None):
|
||||
return ""
|
||||
width = getattr(track, "width", track.height)
|
||||
resolution = min(width, track.height)
|
||||
try:
|
||||
dar = getattr(track, "other_display_aspect_ratio", None) or []
|
||||
if dar and dar[0]:
|
||||
aspect_ratio = [int(float(plane)) for plane in str(dar[0]).split(":")]
|
||||
if len(aspect_ratio) == 1:
|
||||
aspect_ratio.append(1)
|
||||
ratio = aspect_ratio[0] / aspect_ratio[1]
|
||||
if ratio not in (16 / 9, 4 / 3, 9 / 16, 3 / 4):
|
||||
resolution = int(max(width, track.height) * (9 / 16))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
scan_suffix = "i" if str(getattr(track, "scan_type", "")).lower() == "interlaced" else "p"
|
||||
return f"{resolution}{scan_suffix}"
|
||||
|
||||
# Title [Year] SXXEXX Name (or Title [Year] SXX if folder)
|
||||
if folder:
|
||||
name = f"{self.title}"
|
||||
if self.year and config.series_year:
|
||||
name += f" {self.year}"
|
||||
name += f" S{self.season:02}"
|
||||
else:
|
||||
if config.dash_naming:
|
||||
# Format: Title - SXXEXX - Episode Name
|
||||
name = self.title.replace("$", "S") # e.g., Arli$$
|
||||
series_template = config.output_template.get("series")
|
||||
if series_template:
|
||||
folder_template = series_template
|
||||
folder_template = re.sub(r'\{episode\}', '', folder_template)
|
||||
folder_template = re.sub(r'\{episode_name\?\}', '', folder_template)
|
||||
folder_template = re.sub(r'\{episode_name\}', '', folder_template)
|
||||
folder_template = re.sub(r'\{season_episode\}', '{season}', folder_template)
|
||||
|
||||
# Add year if configured
|
||||
if self.year and config.series_year:
|
||||
name += f" {self.year}"
|
||||
folder_template = re.sub(r'\.{2,}', '.', folder_template)
|
||||
folder_template = re.sub(r'\s{2,}', ' ', folder_template)
|
||||
folder_template = re.sub(r'^[\.\s]+|[\.\s]+$', '', folder_template)
|
||||
|
||||
# Add season and episode
|
||||
name += f" - S{self.season:02}E{self.number:02}"
|
||||
formatter = TemplateFormatter(folder_template)
|
||||
context = self._build_template_context(media_info, show_service)
|
||||
context['season'] = f"S{self.season:02}"
|
||||
|
||||
# Add episode name with dash separator
|
||||
if self.name and config.insert_episodename_into_filenames:
|
||||
name += f" - {self.name}"
|
||||
folder_name = formatter.format(context)
|
||||
|
||||
name = name.strip()
|
||||
else:
|
||||
# Standard format without extra dashes
|
||||
name = "{title}{year} S{season:02}E{number:02} {name}".format(
|
||||
title=self.title.replace("$", "S"), # e.g., Arli$$
|
||||
year=f" {self.year}" if self.year and config.series_year else "",
|
||||
season=self.season,
|
||||
number=self.number,
|
||||
name=self.name if self.name and config.insert_episodename_into_filenames else "",
|
||||
).strip()
|
||||
|
||||
if getattr(config, "repack", False):
|
||||
name += " REPACK"
|
||||
|
||||
if self.tracks:
|
||||
first_track = next(iter(self.tracks), None)
|
||||
if first_track and first_track.edition:
|
||||
name += " " + " ".join(first_track.edition)
|
||||
|
||||
if primary_video_track:
|
||||
resolution_token = _get_resolution_token(primary_video_track)
|
||||
if resolution_token:
|
||||
name += f" {resolution_token}"
|
||||
|
||||
# Service (use track source if available)
|
||||
if show_service:
|
||||
source_name = None
|
||||
if self.tracks:
|
||||
first_track = next(iter(self.tracks), None)
|
||||
if first_track and hasattr(first_track, "source") and first_track.source:
|
||||
source_name = first_track.source
|
||||
name += f" {source_name or self.service.__name__}"
|
||||
|
||||
# 'WEB-DL'
|
||||
name += " WEB-DL"
|
||||
|
||||
# DUAL
|
||||
if unique_audio_languages == 2:
|
||||
name += " DUAL"
|
||||
|
||||
# MULTi
|
||||
if unique_audio_languages > 2:
|
||||
name += " MULTi"
|
||||
|
||||
# Audio Codec + Channels (+ feature)
|
||||
if primary_audio_track:
|
||||
codec = primary_audio_track.format
|
||||
channel_layout = primary_audio_track.channel_layout or primary_audio_track.channellayout_original
|
||||
if channel_layout:
|
||||
channels = float(
|
||||
sum({"LFE": 0.1}.get(position.upper(), 1) for position in channel_layout.split(" "))
|
||||
)
|
||||
else:
|
||||
channel_count = primary_audio_track.channel_s or primary_audio_track.channels or 0
|
||||
channels = float(channel_count)
|
||||
|
||||
features = primary_audio_track.format_additionalfeatures or ""
|
||||
name += f" {AUDIO_CODEC_MAP.get(codec, codec)}{channels:.1f}"
|
||||
if "JOC" in features or primary_audio_track.joc:
|
||||
name += " Atmos"
|
||||
|
||||
# Video (dynamic range + hfr +) Codec
|
||||
if primary_video_track:
|
||||
codec = primary_video_track.format
|
||||
hdr_format = primary_video_track.hdr_format_commercial
|
||||
hdr_format_full = primary_video_track.hdr_format or ""
|
||||
trc = (
|
||||
primary_video_track.transfer_characteristics
|
||||
or primary_video_track.transfer_characteristics_original
|
||||
or ""
|
||||
)
|
||||
frame_rate = float(primary_video_track.frame_rate)
|
||||
|
||||
def _append_token(current: str, token: Optional[str]) -> str:
|
||||
token = (token or "").strip()
|
||||
current = current.rstrip()
|
||||
if not token:
|
||||
return current
|
||||
if current.endswith(f" {token}"):
|
||||
return current
|
||||
return f"{current} {token}"
|
||||
|
||||
# Primary HDR format detection
|
||||
if hdr_format:
|
||||
if hdr_format_full.startswith("Dolby Vision"):
|
||||
name = _append_token(name, "DV")
|
||||
if any(
|
||||
indicator in (hdr_format_full + " " + hdr_format)
|
||||
for indicator in ["HDR10", "SMPTE ST 2086"]
|
||||
):
|
||||
name = _append_token(name, "HDR")
|
||||
elif "HDR Vivid" in hdr_format:
|
||||
name = _append_token(name, "HDR")
|
||||
if '.' in series_template and ' ' not in series_template:
|
||||
return sanitize_filename(folder_name, ".")
|
||||
else:
|
||||
dynamic_range = DYNAMIC_RANGE_MAP.get(hdr_format) or hdr_format or ""
|
||||
name = _append_token(name, dynamic_range)
|
||||
elif "HLG" in trc or "Hybrid Log-Gamma" in trc or "ARIB STD-B67" in trc or "arib-std-b67" in trc.lower():
|
||||
name += " HLG"
|
||||
elif any(indicator in trc for indicator in ["PQ", "SMPTE ST 2084", "BT.2100"]) or "smpte2084" in trc.lower() or "bt.2020-10" in trc.lower():
|
||||
name += " HDR"
|
||||
if frame_rate > 30:
|
||||
name += " HFR"
|
||||
name += f" {VIDEO_CODEC_MAP.get(codec, codec)}"
|
||||
return sanitize_filename(folder_name, " ")
|
||||
else:
|
||||
name = f"{self.title}"
|
||||
if self.year:
|
||||
name += f" {self.year}"
|
||||
name += f" S{self.season:02}"
|
||||
return sanitize_filename(name, " ")
|
||||
|
||||
if config.tag:
|
||||
name += f"-{config.tag}"
|
||||
|
||||
return sanitize_filename(name, "." if config.scene_naming else " ")
|
||||
formatter = TemplateFormatter(config.output_template["series"])
|
||||
context = self._build_template_context(media_info, show_service)
|
||||
return formatter.format(context)
|
||||
|
||||
|
||||
class Series(SortedKeyList, ABC):
|
||||
@@ -261,7 +141,7 @@ class Series(SortedKeyList, ABC):
|
||||
def __str__(self) -> str:
|
||||
if not self:
|
||||
return super().__str__()
|
||||
return self[0].title + (f" ({self[0].year})" if self[0].year and config.series_year else "")
|
||||
return self[0].title + (f" ({self[0].year})" if self[0].year else "")
|
||||
|
||||
def tree(self, verbose: bool = False) -> Tree:
|
||||
seasons = Counter(x.season for x in self)
|
||||
|
||||
+16
-136
@@ -7,9 +7,9 @@ from rich.tree import Tree
|
||||
from sortedcontainers import SortedKeyList
|
||||
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.constants import AUDIO_CODEC_MAP, DYNAMIC_RANGE_MAP, VIDEO_CODEC_MAP
|
||||
from unshackle.core.titles.title import Title
|
||||
from unshackle.core.utilities import sanitize_filename
|
||||
from unshackle.core.utils.template_formatter import TemplateFormatter
|
||||
|
||||
|
||||
class Movie(Title):
|
||||
@@ -45,148 +45,28 @@ class Movie(Title):
|
||||
self.year = year
|
||||
self.description = description
|
||||
|
||||
def _build_template_context(self, media_info: MediaInfo, show_service: bool = True) -> dict:
|
||||
"""Build template context dictionary from MediaInfo."""
|
||||
context = self._build_base_template_context(media_info, show_service)
|
||||
context["title"] = self.name.replace("$", "S")
|
||||
context["year"] = self.year or ""
|
||||
return context
|
||||
|
||||
def __str__(self) -> str:
|
||||
if self.year:
|
||||
if config.dash_naming:
|
||||
return f"{self.name} - {self.year}"
|
||||
return f"{self.name} ({self.year})"
|
||||
return self.name
|
||||
|
||||
def get_filename(self, media_info: MediaInfo, folder: bool = False, show_service: bool = True) -> str:
|
||||
primary_video_track = next(iter(media_info.video_tracks), None)
|
||||
primary_audio_track = None
|
||||
if media_info.audio_tracks:
|
||||
sorted_audio = sorted(
|
||||
media_info.audio_tracks,
|
||||
key=lambda x: (
|
||||
float(x.bit_rate) if x.bit_rate else 0,
|
||||
bool(x.format_additionalfeatures and "JOC" in x.format_additionalfeatures),
|
||||
),
|
||||
reverse=True,
|
||||
)
|
||||
primary_audio_track = sorted_audio[0]
|
||||
unique_audio_languages = len({x.language.split("-")[0] for x in media_info.audio_tracks if x.language})
|
||||
if folder:
|
||||
name = f"{self.name}"
|
||||
if self.year:
|
||||
name += f" ({self.year})"
|
||||
return sanitize_filename(name, " ")
|
||||
|
||||
def _get_resolution_token(track: Any) -> str:
|
||||
if not track or not getattr(track, "height", None):
|
||||
return ""
|
||||
width = getattr(track, "width", track.height)
|
||||
resolution = min(width, track.height)
|
||||
try:
|
||||
dar = getattr(track, "other_display_aspect_ratio", None) or []
|
||||
if dar and dar[0]:
|
||||
aspect_ratio = [int(float(plane)) for plane in str(dar[0]).split(":")]
|
||||
if len(aspect_ratio) == 1:
|
||||
aspect_ratio.append(1)
|
||||
ratio = aspect_ratio[0] / aspect_ratio[1]
|
||||
if ratio not in (16 / 9, 4 / 3, 9 / 16, 3 / 4):
|
||||
resolution = int(max(width, track.height) * (9 / 16))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
scan_suffix = "i" if str(getattr(track, "scan_type", "")).lower() == "interlaced" else "p"
|
||||
return f"{resolution}{scan_suffix}"
|
||||
|
||||
# Name (Year)
|
||||
name = str(self).replace("$", "S") # e.g., Arli$$
|
||||
|
||||
if getattr(config, "repack", False):
|
||||
name += " REPACK"
|
||||
|
||||
if self.tracks:
|
||||
first_track = next(iter(self.tracks), None)
|
||||
if first_track and first_track.edition:
|
||||
name += " " + " ".join(first_track.edition)
|
||||
|
||||
if primary_video_track:
|
||||
resolution_token = _get_resolution_token(primary_video_track)
|
||||
if resolution_token:
|
||||
name += f" {resolution_token}"
|
||||
|
||||
# Service (use track source if available)
|
||||
if show_service:
|
||||
source_name = None
|
||||
if self.tracks:
|
||||
first_track = next(iter(self.tracks), None)
|
||||
if first_track and hasattr(first_track, "source") and first_track.source:
|
||||
source_name = first_track.source
|
||||
name += f" {source_name or self.service.__name__}"
|
||||
|
||||
# 'WEB-DL'
|
||||
name += " WEB-DL"
|
||||
|
||||
# DUAL
|
||||
if unique_audio_languages == 2:
|
||||
name += " DUAL"
|
||||
|
||||
# MULTi
|
||||
if unique_audio_languages > 2:
|
||||
name += " MULTi"
|
||||
|
||||
# Audio Codec + Channels (+ feature)
|
||||
if primary_audio_track:
|
||||
codec = primary_audio_track.format
|
||||
channel_layout = primary_audio_track.channel_layout or primary_audio_track.channellayout_original
|
||||
if channel_layout:
|
||||
channels = float(
|
||||
sum({"LFE": 0.1}.get(position.upper(), 1) for position in channel_layout.split(" "))
|
||||
)
|
||||
else:
|
||||
channel_count = primary_audio_track.channel_s or primary_audio_track.channels or 0
|
||||
channels = float(channel_count)
|
||||
|
||||
features = primary_audio_track.format_additionalfeatures or ""
|
||||
name += f" {AUDIO_CODEC_MAP.get(codec, codec)}{channels:.1f}"
|
||||
if "JOC" in features or primary_audio_track.joc:
|
||||
name += " Atmos"
|
||||
|
||||
# Video (dynamic range + hfr +) Codec
|
||||
if primary_video_track:
|
||||
codec = primary_video_track.format
|
||||
hdr_format = primary_video_track.hdr_format_commercial
|
||||
hdr_format_full = primary_video_track.hdr_format or ""
|
||||
trc = (
|
||||
primary_video_track.transfer_characteristics
|
||||
or primary_video_track.transfer_characteristics_original
|
||||
or ""
|
||||
)
|
||||
frame_rate = float(primary_video_track.frame_rate)
|
||||
|
||||
def _append_token(current: str, token: Optional[str]) -> str:
|
||||
token = (token or "").strip()
|
||||
current = current.rstrip()
|
||||
if not token:
|
||||
return current
|
||||
if current.endswith(f" {token}"):
|
||||
return current
|
||||
return f"{current} {token}"
|
||||
|
||||
# Primary HDR format detection
|
||||
if hdr_format:
|
||||
if hdr_format_full.startswith("Dolby Vision"):
|
||||
name = _append_token(name, "DV")
|
||||
if any(
|
||||
indicator in (hdr_format_full + " " + hdr_format)
|
||||
for indicator in ["HDR10", "SMPTE ST 2086"]
|
||||
):
|
||||
name = _append_token(name, "HDR")
|
||||
elif "HDR Vivid" in hdr_format:
|
||||
name = _append_token(name, "HDR")
|
||||
else:
|
||||
dynamic_range = DYNAMIC_RANGE_MAP.get(hdr_format) or hdr_format or ""
|
||||
name = _append_token(name, dynamic_range)
|
||||
elif "HLG" in trc or "Hybrid Log-Gamma" in trc or "ARIB STD-B67" in trc or "arib-std-b67" in trc.lower():
|
||||
name += " HLG"
|
||||
elif any(indicator in trc for indicator in ["PQ", "SMPTE ST 2084", "BT.2100"]) or "smpte2084" in trc.lower() or "bt.2020-10" in trc.lower():
|
||||
name += " HDR"
|
||||
if frame_rate > 30:
|
||||
name += " HFR"
|
||||
name += f" {VIDEO_CODEC_MAP.get(codec, codec)}"
|
||||
|
||||
if config.tag:
|
||||
name += f"-{config.tag}"
|
||||
|
||||
return sanitize_filename(name, "." if config.scene_naming else " ")
|
||||
formatter = TemplateFormatter(config.output_template["movies"])
|
||||
context = self._build_template_context(media_info, show_service)
|
||||
return formatter.format(context)
|
||||
|
||||
|
||||
class Movies(SortedKeyList, ABC):
|
||||
|
||||
@@ -7,9 +7,9 @@ from rich.tree import Tree
|
||||
from sortedcontainers import SortedKeyList
|
||||
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.constants import AUDIO_CODEC_MAP
|
||||
from unshackle.core.titles.title import Title
|
||||
from unshackle.core.utilities import sanitize_filename
|
||||
from unshackle.core.utils.template_formatter import TemplateFormatter
|
||||
|
||||
|
||||
class Song(Title):
|
||||
@@ -41,7 +41,7 @@ class Song(Title):
|
||||
if not album:
|
||||
raise ValueError("Song album must be provided")
|
||||
if not isinstance(album, str):
|
||||
raise TypeError(f"Expected album to be a str, not {name!r}")
|
||||
raise TypeError(f"Expected album to be a str, not {album!r}")
|
||||
|
||||
if not track:
|
||||
raise ValueError("Song track must be provided")
|
||||
@@ -81,54 +81,27 @@ class Song(Title):
|
||||
artist=self.artist, album=self.album, year=self.year, track=self.track, name=self.name
|
||||
).strip()
|
||||
|
||||
def _build_template_context(self, media_info: MediaInfo, show_service: bool = True) -> dict:
|
||||
"""Build template context dictionary from MediaInfo."""
|
||||
context = self._build_base_template_context(media_info, show_service)
|
||||
context["title"] = self.name.replace("$", "S")
|
||||
context["year"] = self.year or ""
|
||||
context["track_number"] = f"{self.track:02}"
|
||||
context["artist"] = self.artist.replace("$", "S")
|
||||
context["album"] = self.album.replace("$", "S")
|
||||
context["disc"] = f"{self.disc:02}" if self.disc > 1 else ""
|
||||
return context
|
||||
|
||||
def get_filename(self, media_info: MediaInfo, folder: bool = False, show_service: bool = True) -> str:
|
||||
audio_track = next(iter(media_info.audio_tracks), None)
|
||||
codec = audio_track.format
|
||||
channel_layout = audio_track.channel_layout or audio_track.channellayout_original
|
||||
if channel_layout:
|
||||
channels = float(sum({"LFE": 0.1}.get(position.upper(), 1) for position in channel_layout.split(" ")))
|
||||
else:
|
||||
channel_count = audio_track.channel_s or audio_track.channels or 0
|
||||
channels = float(channel_count)
|
||||
|
||||
features = audio_track.format_additionalfeatures or ""
|
||||
|
||||
if folder:
|
||||
# Artist - Album (Year)
|
||||
name = str(self).split(" / ")[0]
|
||||
else:
|
||||
# NN. Song Name
|
||||
name = str(self).split(" / ")[1]
|
||||
name = f"{self.artist} - {self.album}"
|
||||
if self.year:
|
||||
name += f" ({self.year})"
|
||||
return sanitize_filename(name, " ")
|
||||
|
||||
if getattr(config, "repack", False):
|
||||
name += " REPACK"
|
||||
|
||||
if self.tracks:
|
||||
first_track = next(iter(self.tracks), None)
|
||||
if first_track and first_track.edition:
|
||||
name += " " + " ".join(first_track.edition)
|
||||
|
||||
# Service (use track source if available)
|
||||
if show_service:
|
||||
source_name = None
|
||||
if self.tracks:
|
||||
first_track = next(iter(self.tracks), None)
|
||||
if first_track and hasattr(first_track, "source") and first_track.source:
|
||||
source_name = first_track.source
|
||||
name += f" {source_name or self.service.__name__}"
|
||||
|
||||
# 'WEB-DL'
|
||||
name += " WEB-DL"
|
||||
|
||||
# Audio Codec + Channels (+ feature)
|
||||
name += f" {AUDIO_CODEC_MAP.get(codec, codec)}{channels:.1f}"
|
||||
if "JOC" in features or audio_track.joc:
|
||||
name += " Atmos"
|
||||
|
||||
if config.tag:
|
||||
name += f"-{config.tag}"
|
||||
|
||||
return sanitize_filename(name, " ")
|
||||
formatter = TemplateFormatter(config.output_template["songs"])
|
||||
context = self._build_template_context(media_info, show_service)
|
||||
return formatter.format(context)
|
||||
|
||||
|
||||
class Album(SortedKeyList, ABC):
|
||||
|
||||
@@ -6,6 +6,8 @@ from typing import Any, Optional, Union
|
||||
from langcodes import Language
|
||||
from pymediainfo import MediaInfo
|
||||
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.constants import AUDIO_CODEC_MAP, DYNAMIC_RANGE_MAP, VIDEO_CODEC_MAP
|
||||
from unshackle.core.tracks import Tracks
|
||||
|
||||
|
||||
@@ -51,6 +53,125 @@ class Title:
|
||||
def __eq__(self, other: Title) -> bool:
|
||||
return self.id == other.id
|
||||
|
||||
def _build_base_template_context(self, media_info: MediaInfo, show_service: bool = True) -> dict:
|
||||
"""Build base template context dictionary from MediaInfo.
|
||||
|
||||
Extracts video, audio, HDR, HFR, and multi-language information shared
|
||||
across all title types. Subclasses should call this and extend the
|
||||
returned dict with their specific fields (e.g., season/episode).
|
||||
"""
|
||||
primary_video_track = next(iter(media_info.video_tracks), None)
|
||||
primary_audio_track = next(iter(media_info.audio_tracks), None)
|
||||
unique_audio_languages = len({x.language.split("-")[0] for x in media_info.audio_tracks if x.language})
|
||||
|
||||
context: dict[str, Any] = {
|
||||
"source": self.service.__name__ if show_service else "",
|
||||
"tag": config.tag or "",
|
||||
"repack": "REPACK" if getattr(config, "repack", False) else "",
|
||||
"quality": "",
|
||||
"resolution": "",
|
||||
"audio": "",
|
||||
"audio_channels": "",
|
||||
"audio_full": "",
|
||||
"atmos": "",
|
||||
"dual": "",
|
||||
"multi": "",
|
||||
"video": "",
|
||||
"hdr": "",
|
||||
"hfr": "",
|
||||
"edition": "",
|
||||
"lang_tag": "",
|
||||
}
|
||||
|
||||
if self.tracks:
|
||||
first_track = next(iter(self.tracks), None)
|
||||
if first_track and first_track.edition:
|
||||
context["edition"] = " ".join(first_track.edition)
|
||||
|
||||
if primary_video_track:
|
||||
width = getattr(primary_video_track, "width", primary_video_track.height)
|
||||
resolution = min(width, primary_video_track.height)
|
||||
try:
|
||||
dar = getattr(primary_video_track, "other_display_aspect_ratio", None) or []
|
||||
if dar and dar[0]:
|
||||
aspect_ratio = [int(float(plane)) for plane in str(dar[0]).split(":")]
|
||||
if len(aspect_ratio) == 1:
|
||||
aspect_ratio.append(1)
|
||||
ratio = aspect_ratio[0] / aspect_ratio[1]
|
||||
if ratio not in (16 / 9, 4 / 3, 9 / 16, 3 / 4):
|
||||
resolution = int(max(width, primary_video_track.height) * (9 / 16))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
scan_suffix = "i" if str(getattr(primary_video_track, "scan_type", "")).lower() == "interlaced" else "p"
|
||||
|
||||
context.update(
|
||||
{
|
||||
"quality": f"{resolution}{scan_suffix}",
|
||||
"resolution": str(resolution),
|
||||
"video": VIDEO_CODEC_MAP.get(primary_video_track.format, primary_video_track.format),
|
||||
}
|
||||
)
|
||||
|
||||
hdr_format = primary_video_track.hdr_format_commercial
|
||||
trc = primary_video_track.transfer_characteristics or primary_video_track.transfer_characteristics_original
|
||||
if hdr_format:
|
||||
if (primary_video_track.hdr_format or "").startswith("Dolby Vision"):
|
||||
context["hdr"] = "DV"
|
||||
base_layer = DYNAMIC_RANGE_MAP.get(hdr_format)
|
||||
if base_layer and base_layer != "DV":
|
||||
context["hdr"] += f".{base_layer}"
|
||||
else:
|
||||
context["hdr"] = DYNAMIC_RANGE_MAP.get(hdr_format, "")
|
||||
elif trc and "HLG" in trc:
|
||||
context["hdr"] = "HLG"
|
||||
else:
|
||||
context["hdr"] = ""
|
||||
|
||||
frame_rate = float(primary_video_track.frame_rate) if primary_video_track.frame_rate else 0.0
|
||||
context["hfr"] = "HFR" if frame_rate > 30 else ""
|
||||
|
||||
if primary_audio_track:
|
||||
codec = primary_audio_track.format
|
||||
channel_layout = primary_audio_track.channel_layout or primary_audio_track.channellayout_original
|
||||
|
||||
if channel_layout:
|
||||
channels = float(sum({"LFE": 0.1}.get(position.upper(), 1) for position in channel_layout.split(" ")))
|
||||
else:
|
||||
channel_count = primary_audio_track.channel_s or primary_audio_track.channels or 0
|
||||
channels = float(channel_count)
|
||||
|
||||
features = primary_audio_track.format_additionalfeatures or ""
|
||||
|
||||
context.update(
|
||||
{
|
||||
"audio": AUDIO_CODEC_MAP.get(codec, codec),
|
||||
"audio_channels": f"{channels:.1f}",
|
||||
"audio_full": f"{AUDIO_CODEC_MAP.get(codec, codec)}{channels:.1f}",
|
||||
"atmos": "Atmos" if ("JOC" in features or primary_audio_track.joc) else "",
|
||||
}
|
||||
)
|
||||
|
||||
if unique_audio_languages == 2:
|
||||
context["dual"] = "DUAL"
|
||||
context["multi"] = ""
|
||||
elif unique_audio_languages > 2:
|
||||
context["dual"] = ""
|
||||
context["multi"] = "MULTi"
|
||||
else:
|
||||
context["dual"] = ""
|
||||
context["multi"] = ""
|
||||
|
||||
lang_tag_rules = config.language_tags.get("rules") if config.language_tags else None
|
||||
if lang_tag_rules and self.tracks:
|
||||
from unshackle.core.utils.language_tags import evaluate_language_tag
|
||||
|
||||
audio_langs = [a.language for a in self.tracks.audio]
|
||||
sub_langs = [s.language for s in self.tracks.subtitles]
|
||||
context["lang_tag"] = evaluate_language_tag(lang_tag_rules, audio_langs, sub_langs)
|
||||
|
||||
return context
|
||||
|
||||
@abstractmethod
|
||||
def get_filename(self, media_info: MediaInfo, folder: bool = False, show_service: bool = True) -> str:
|
||||
"""
|
||||
|
||||
@@ -136,7 +136,7 @@ def sanitize_filename(filename: str, spacer: str = ".") -> str:
|
||||
if spacer == ".":
|
||||
filename = re.sub(r" - ", spacer, filename) # title separators to spacer (avoids .-. pattern)
|
||||
filename = re.sub(r"[:; ]", spacer, filename) # structural chars to (spacer)
|
||||
filename = re.sub(r"[\\*!?¿,'\"" "()<>|$#~]", "", filename) # not filename safe chars
|
||||
filename = re.sub(r"[\\*!?¿,'\"" "<>|$#~]", "", filename) # not filename safe chars
|
||||
filename = re.sub(rf"[{spacer}]{{2,}}", spacer, filename) # remove extra neighbouring (spacer)s
|
||||
|
||||
return filename
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
"""Language tag rule engine for output filename templates."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any, Sequence
|
||||
|
||||
from langcodes import Language
|
||||
|
||||
from unshackle.core.utilities import is_close_match
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def evaluate_language_tag(
|
||||
rules: list[dict[str, Any]],
|
||||
audio_languages: Sequence[Language],
|
||||
subtitle_languages: Sequence[Language],
|
||||
) -> 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.
|
||||
|
||||
Args:
|
||||
rules: List of rule dicts from config, each with conditions and a ``tag``.
|
||||
audio_languages: Languages of the selected audio tracks.
|
||||
subtitle_languages: Languages of the selected subtitle tracks.
|
||||
|
||||
Returns:
|
||||
The tag string from the first matching rule, or ``""`` if none match.
|
||||
"""
|
||||
for rule in rules:
|
||||
tag = rule.get("tag")
|
||||
if not tag:
|
||||
log.warning("Language tag rule missing 'tag' field, skipping: %s", rule)
|
||||
continue
|
||||
|
||||
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(
|
||||
rule: dict[str, Any],
|
||||
audio_languages: Sequence[Language],
|
||||
subtitle_languages: Sequence[Language],
|
||||
) -> bool:
|
||||
"""Check if all conditions in a rule are satisfied."""
|
||||
has_condition = False
|
||||
|
||||
audio_lang = rule.get("audio")
|
||||
if audio_lang is not None:
|
||||
has_condition = True
|
||||
if not is_close_match(audio_lang, list(audio_languages)):
|
||||
return False
|
||||
|
||||
subs_contain = rule.get("subs_contain")
|
||||
if subs_contain is not None:
|
||||
has_condition = True
|
||||
if not is_close_match(subs_contain, list(subtitle_languages)):
|
||||
return False
|
||||
|
||||
subs_contain_all = rule.get("subs_contain_all")
|
||||
if subs_contain_all is not None:
|
||||
has_condition = True
|
||||
if not isinstance(subs_contain_all, list):
|
||||
subs_contain_all = [subs_contain_all]
|
||||
for lang in subs_contain_all:
|
||||
if not is_close_match(lang, list(subtitle_languages)):
|
||||
return False
|
||||
|
||||
if not has_condition:
|
||||
log.warning("Language tag rule has no conditions, skipping: %s", rule)
|
||||
return False
|
||||
|
||||
return True
|
||||
@@ -0,0 +1,162 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from unshackle.core.utilities import sanitize_filename
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class TemplateFormatter:
|
||||
"""
|
||||
Template formatter for custom filename patterns.
|
||||
|
||||
Supports variable substitution and conditional variables.
|
||||
Example: '{title}.{year}.{quality?}.{source}-{tag}'
|
||||
"""
|
||||
|
||||
def __init__(self, template: str):
|
||||
"""Initialize the template formatter.
|
||||
|
||||
Args:
|
||||
template: Template string with variables in {variable} format
|
||||
"""
|
||||
self.template = template
|
||||
self.variables = self._extract_variables()
|
||||
|
||||
def _extract_variables(self) -> list[str]:
|
||||
"""Extract all variables from the template."""
|
||||
pattern = r"\{([^}]+)\}"
|
||||
matches = re.findall(pattern, self.template)
|
||||
return [match.strip() for match in matches]
|
||||
|
||||
def format(self, context: dict[str, Any]) -> str:
|
||||
"""Format the template with the provided context.
|
||||
|
||||
Args:
|
||||
context: Dictionary containing variable values
|
||||
|
||||
Returns:
|
||||
Formatted filename string
|
||||
|
||||
Raises:
|
||||
ValueError: If required template variables are missing from context
|
||||
"""
|
||||
is_valid, missing_vars = self.validate(context)
|
||||
if not is_valid:
|
||||
error_msg = f"Missing required template variables: {', '.join(missing_vars)}"
|
||||
log.error(error_msg)
|
||||
raise ValueError(error_msg)
|
||||
|
||||
try:
|
||||
result = self.template
|
||||
|
||||
for variable in self.variables:
|
||||
placeholder = "{" + variable + "}"
|
||||
is_conditional = variable.endswith("?")
|
||||
|
||||
if is_conditional:
|
||||
var_name = variable[:-1]
|
||||
value = context.get(var_name, "")
|
||||
|
||||
if value:
|
||||
safe_value = str(value).strip()
|
||||
result = result.replace(placeholder, safe_value)
|
||||
else:
|
||||
# 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:
|
||||
s = m.group(0)
|
||||
has_left = s[0] in ".- "
|
||||
has_right = s[-1] in ".- "
|
||||
if has_left and has_right:
|
||||
return s[0] # keep left separator
|
||||
return ""
|
||||
|
||||
result = re.sub(
|
||||
rf"[\.\s\-]?{re.escape(placeholder)}[\.\s\-]?",
|
||||
_remove_conditional,
|
||||
result,
|
||||
count=1,
|
||||
)
|
||||
else:
|
||||
value = context.get(variable, "")
|
||||
if value is None:
|
||||
log.warning(f"Template variable '{variable}' is None, using empty string")
|
||||
value = ""
|
||||
|
||||
safe_value = str(value).strip()
|
||||
result = result.replace(placeholder, safe_value)
|
||||
|
||||
# Clean up multiple consecutive dots/separators and other artifacts
|
||||
result = re.sub(r"\.{2,}", ".", result) # Multiple dots -> single dot
|
||||
result = re.sub(r"\s{2,}", " ", result) # Multiple spaces -> single space
|
||||
result = re.sub(r"-{2,}", "-", result) # Multiple dashes -> single dash
|
||||
result = re.sub(r"^[\.\s\-]+|[\.\s\-]+$", "", result) # Remove leading/trailing dots, spaces, dashes
|
||||
result = re.sub(r"\.-", "-", result) # Remove dots before dashes (for dot-based templates)
|
||||
result = re.sub(r"[\.\s]+\)", ")", result) # Remove dots/spaces before closing parentheses
|
||||
result = re.sub(r"\(\s*\)", "", result) # Remove empty parentheses (empty conditional)
|
||||
|
||||
# Determine the appropriate separator based on template style
|
||||
# Count separator characters between variables (between } and {)
|
||||
between_vars = re.findall(r"\}([^{]*)\{", self.template)
|
||||
separator_text = "".join(between_vars)
|
||||
dot_count = separator_text.count(".")
|
||||
space_count = separator_text.count(" ")
|
||||
|
||||
if space_count > dot_count:
|
||||
result = sanitize_filename(result, spacer=" ")
|
||||
else:
|
||||
result = sanitize_filename(result, spacer=".")
|
||||
|
||||
if not result or result.isspace():
|
||||
log.warning("Template formatting resulted in empty filename, using fallback")
|
||||
return "untitled"
|
||||
|
||||
log.debug(f"Template formatted successfully: '{self.template}' -> '{result}'")
|
||||
return result
|
||||
|
||||
except (KeyError, ValueError, re.error) as e:
|
||||
log.error(f"Error formatting template '{self.template}': {e}")
|
||||
fallback = f"error_formatting_{hash(self.template) % 10000}"
|
||||
log.warning(f"Using fallback filename: {fallback}")
|
||||
return fallback
|
||||
|
||||
def validate(self, context: dict[str, Any]) -> tuple[bool, list[str]]:
|
||||
"""Validate that all required variables are present in context.
|
||||
|
||||
Args:
|
||||
context: Dictionary containing variable values
|
||||
|
||||
Returns:
|
||||
Tuple of (is_valid, missing_variables)
|
||||
"""
|
||||
missing = []
|
||||
|
||||
for variable in self.variables:
|
||||
is_conditional = variable.endswith("?")
|
||||
var_name = variable[:-1] if is_conditional else variable
|
||||
|
||||
if not is_conditional and var_name not in context:
|
||||
missing.append(var_name)
|
||||
|
||||
return len(missing) == 0, missing
|
||||
|
||||
def get_required_variables(self) -> list[str]:
|
||||
"""Get list of required (non-conditional) variables."""
|
||||
required = []
|
||||
for variable in self.variables:
|
||||
if not variable.endswith("?"):
|
||||
required.append(variable)
|
||||
return required
|
||||
|
||||
def get_optional_variables(self) -> list[str]:
|
||||
"""Get list of optional (conditional) variables."""
|
||||
optional = []
|
||||
for variable in self.variables:
|
||||
if variable.endswith("?"):
|
||||
optional.append(variable[:-1]) # Remove the ?
|
||||
return optional
|
||||
@@ -17,15 +17,66 @@ tag_imdb_tmdb: true
|
||||
# Set terminal background color (custom option not in CONFIG.md)
|
||||
set_terminal_bg: false
|
||||
|
||||
# Set file naming convention
|
||||
# true for style - Prime.Suspect.S07E01.The.Final.Act.Part.One.1080p.ITV.WEB-DL.AAC2.0.H.264
|
||||
# false for style - Prime Suspect S07E01 The Final Act - Part One
|
||||
scene_naming: true
|
||||
# Custom output templates for filenames
|
||||
# Configure output_template in your unshackle.yaml to control filename format.
|
||||
# If not configured, default scene-style templates are used and a warning is shown.
|
||||
# Available variables: {title}, {year}, {season}, {episode}, {season_episode}, {episode_name},
|
||||
# {quality}, {resolution}, {source}, {audio}, {audio_channels}, {audio_full},
|
||||
# {video}, {hdr}, {hfr}, {atmos}, {dual}, {multi}, {tag}, {edition}, {repack},
|
||||
# {lang_tag}
|
||||
# Conditional variables (included only if present): Add ? suffix like {year?}, {episode_name?}, {hdr?}
|
||||
# Customize the templates below:
|
||||
#
|
||||
# Example outputs:
|
||||
# Scene movies: 'The.Matrix.1999.1080p.SERVICE.WEB-DL.DDP5.1.H.264-EXAMPLE'
|
||||
# Scene movies (HDR): 'Dune.2021.2160p.SERVICE.WEB-DL.DDP5.1.HDR10.H.265-EXAMPLE'
|
||||
# Scene movies (REPACK): 'Dune.2021.REPACK.2160p.SERVICE.WEB-DL.DDP5.1.H.265-EXAMPLE'
|
||||
# Scene series: 'Breaking.Bad.2008.S01E01.Pilot.1080p.SERVICE.WEB-DL.DDP5.1.H.264-EXAMPLE'
|
||||
# Plex movies: 'The Matrix (1999) 1080p'
|
||||
# Plex series: 'Breaking Bad S01E01 Pilot'
|
||||
output_template:
|
||||
# Scene-style naming (dot-separated)
|
||||
movies: '{title}.{year}.{repack?}.{edition?}.{quality}.{source}.WEB-DL.{dual?}.{multi?}.{audio_full}.{atmos?}.{hdr?}.{hfr?}.{video}-{tag}'
|
||||
series: '{title}.{year?}.{season_episode}.{episode_name?}.{repack?}.{edition?}.{quality}.{source}.WEB-DL.{dual?}.{multi?}.{audio_full}.{atmos?}.{hdr?}.{hfr?}.{video}-{tag}'
|
||||
songs: '{track_number}.{title}.{repack?}.{edition?}.{source?}.WEB-DL.{audio_full}.{atmos?}-{tag}'
|
||||
#
|
||||
# Plex-friendly naming (space-separated, clean format)
|
||||
# movies: '{title} ({year}) {quality}'
|
||||
# series: '{title} {season_episode} {episode_name?}'
|
||||
# songs: '{track_number}. {title}'
|
||||
#
|
||||
# Minimal naming (basic info only)
|
||||
# movies: '{title}.{year}.{quality}'
|
||||
# series: '{title}.{season_episode}.{episode_name?}'
|
||||
#
|
||||
# Custom scene-style with specific elements
|
||||
# movies: '{title}.{year}.{quality}.{hdr?}.{source}.WEB-DL.{audio_full}.{video}-{tag}'
|
||||
# series: '{title}.{year?}.{season_episode}.{episode_name?}.{quality}.{hdr?}.{source}.WEB-DL.{audio_full}.{atmos?}.{video}-{tag}'
|
||||
|
||||
# Whether to include the year in series names for episodes and folders (default: true)
|
||||
# true for style - Show Name (2023) S01E01 Episode Name
|
||||
# false for style - Show Name S01E01 Episode Name
|
||||
series_year: true
|
||||
# Language-based tagging for output filenames
|
||||
# Automatically adds language identifiers (e.g., DANiSH, NORDiC, DKsubs) based on
|
||||
# audio and subtitle track languages. Rules are evaluated in order; first match wins.
|
||||
# Use {lang_tag?} in your output_template to place the tag in the filename.
|
||||
#
|
||||
# Conditions (all conditions in a rule must match):
|
||||
# audio: <lang> - any audio track matches this language
|
||||
# subs_contain: <lang> - any subtitle matches this language
|
||||
# subs_contain_all: [lang, ...] - subtitles include ALL listed languages
|
||||
#
|
||||
# language_tags:
|
||||
# rules:
|
||||
# - audio: da
|
||||
# tag: DANiSH
|
||||
# - audio: sv
|
||||
# tag: SWEDiSH
|
||||
# - audio: nb
|
||||
# tag: NORWEGiAN
|
||||
# - audio: en
|
||||
# subs_contain_all: [da, sv, nb]
|
||||
# tag: NORDiC
|
||||
# - audio: en
|
||||
# subs_contain: da
|
||||
# tag: DKsubs
|
||||
|
||||
# Check for updates from GitHub repository on startup (default: true)
|
||||
update_checks: true
|
||||
@@ -41,7 +92,6 @@ title_cache_max_retention: 86400 # Maximum cache retention for fallback when API
|
||||
|
||||
# Filename Configuration
|
||||
unicode_filenames: false # optionally replace non-ASCII characters with ASCII equivalents
|
||||
insert_episodename_into_filenames: true # optionally determines whether the specific name of an episode is automatically included within the filename for series content.
|
||||
|
||||
# Debug logging configuration
|
||||
# Comprehensive JSON-based debug logging for troubleshooting and service development
|
||||
|
||||
@@ -1259,22 +1259,22 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "pyplayready"
|
||||
version = "0.6.3"
|
||||
version = "0.8.3"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "aiohttp" },
|
||||
{ name = "click" },
|
||||
{ name = "construct" },
|
||||
{ name = "cryptography" },
|
||||
{ name = "ecpy" },
|
||||
{ name = "lxml" },
|
||||
{ name = "platformdirs" },
|
||||
{ name = "pycryptodome" },
|
||||
{ name = "pyyaml" },
|
||||
{ name = "requests" },
|
||||
{ name = "xmltodict" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/53/f2/6d75b6d10a8361b53a2acbe959d51aa586418e9af497381a9f5c436ca488/pyplayready-0.6.3.tar.gz", hash = "sha256:b9b82a32c2cced9c43f910eb1fb891545f1491dc063c1eb9c20634e2417eda76", size = 58019, upload-time = "2025-08-20T19:32:43.642Z" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/99/7a/5c83dd76a3e1cf5158f7cc7a62193a5a329acce3e2a8237cd921ac5c6b31/pyplayready-0.8.3.tar.gz", hash = "sha256:a86b6cee37fa502e49e5b6956a0086de677afff82507ed34a4507eac8fa563af", size = 67517, upload-time = "2026-02-26T21:06:33.213Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/5b/7f/64d5ff5d765f9f2138ee7cc196fd9401f9eae0fb514c66660ad4e56584fa/pyplayready-0.6.3-py3-none-any.whl", hash = "sha256:82f35434e790a7da21df57ec053a2924ceb63622c5a6c5ff9f0fa03db0531c57", size = 66162, upload-time = "2025-08-20T19:32:42.62Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/26/f0/8dc65e90a21ec65b52278d1017d7abbff763f536ca168a687a1a60d2deb8/pyplayready-0.8.3-py3-none-any.whl", hash = "sha256:995ea335998cc63890f24959e9ab88cd5ef962a507396f1097badc843bc7be9e", size = 78016, upload-time = "2026-02-26T21:06:32.008Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1715,7 +1715,7 @@ requires-dist = [
|
||||
{ name = "pymediainfo", specifier = ">=6.1.0,<8" },
|
||||
{ name = "pymp4", specifier = ">=1.4.0,<2" },
|
||||
{ name = "pymysql", specifier = ">=1.1.0,<2" },
|
||||
{ name = "pyplayready", specifier = ">=0.6.3,<0.7" },
|
||||
{ name = "pyplayready", specifier = ">=0.8.3,<0.9" },
|
||||
{ name = "pysubs2", specifier = ">=1.7.0,<2" },
|
||||
{ name = "pywidevine", extras = ["serve"], specifier = ">=1.8.0,<2" },
|
||||
{ name = "pyyaml", specifier = ">=6.0.1,<7" },
|
||||
@@ -1796,15 +1796,6 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/4f/bc/ab575ebf0254577034d23908299b0d13ea5d7ceb35f43a5c08acf2252826/wcwidth-0.3.3-py3-none-any.whl", hash = "sha256:8e9056c446f21c7393514946d143a748c56aad72476844d3f215f7915276508f", size = 86509, upload-time = "2026-01-24T16:23:56.966Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "xmltodict"
|
||||
version = "0.14.2"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/50/05/51dcca9a9bf5e1bce52582683ce50980bcadbc4fa5143b9f2b19ab99958f/xmltodict-0.14.2.tar.gz", hash = "sha256:201e7c28bb210e374999d1dde6382923ab0ed1a8a5faeece48ab525b7810a553", size = 51942, upload-time = "2024-10-16T06:10:29.683Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/d6/45/fc303eb433e8a2a271739c98e953728422fa61a3c1f36077a49e395c972e/xmltodict-0.14.2-py2.py3-none-any.whl", hash = "sha256:20cc7d723ed729276e808f26fb6b3599f786cbc37e06c65e192ba77c40f20aac", size = 9981, upload-time = "2024-10-16T06:10:27.649Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "yarl"
|
||||
version = "1.22.0"
|
||||
|
||||
Reference in New Issue
Block a user