feat(config): add filename_replacements to replace text in output names

This commit is contained in:
imSp4rky
2026-11-28 15:03:01 -07:00
parent 127e8e0dcc
commit 418d69b1ec
9 changed files with 115 additions and 10 deletions
+1 -1
View File
@@ -590,7 +590,7 @@ unicode_filenames: true
With each value, unshackle first normalises the name to Unicode NFC. A title that a service sends in composed form and in decomposed form gives the same name.
Regardless of this setting, unshackle always removes or replaces a set of filesystem-unsafe and structural characters during sanitisation. For example, `/` and `;` become ` & `, and unshackle removes characters like `\ * ! ? , ' " < > | $ # ~`. This is why you must never put path-unsafe characters directly in a template.
Regardless of this setting, unshackle always removes or replaces a set of filesystem-unsafe and structural characters during sanitisation. For example, `/` and `;` become ` & `, and unshackle removes characters like `\ * ! ? , ' " < > | $ # ~`. This is why you must never put path-unsafe characters directly in a template. To change other text in a name, such as `&` to `and`, use [`filename_replacements`](../reference/configuration/output.md#filename_replacements).
unshackle warns at startup about a template that contains `< > : " / \ | ? *`. It examines a folder template per path segment, so you can use `/` there as a directory separator.
+1 -1
View File
@@ -32,7 +32,7 @@ Where the file lives, how unshackle discovers it, and how to edit it:
| [Directories](directories.md) | `directories`, `filenames`, `services_repo_force` |
| [Services & authentication](services.md) | `services`, `credentials`, `firefox_cookies`, `remote_services`, `serve` |
| [Download & processing](download.md) | `dl`, `continue_downloads`, `merge_segments`, `subtitle`, `audio`, `muxing`, `language_tags`, `dual_multi_mode`, `generate_dv_mode`, `hdr10plus_probe` |
| [Output & naming](output.md) | `output_template`, `tag`, `tag_rules`, `codec_names`, `tag_group_name`, `tag_imdb_tmdb`, `chapter_fallback_name`, `unicode_filenames` |
| [Output & naming](output.md) | `output_template`, `tag`, `tag_rules`, `codec_names`, `tag_group_name`, `tag_imdb_tmdb`, `chapter_fallback_name`, `unicode_filenames`, `filename_replacements` |
| [DRM & CDM](drm.md) | `cdm`, `remote_cdm`, `decryption` |
| [Network & proxy](network.md) | `network`, `headers`, `proxy_providers` |
| [Key vaults](vaults.md) | `key_vaults`, `vault_timeout` |
+29
View File
@@ -77,6 +77,7 @@ folder-kind keys.
| `tag_imdb_tmdb` | bool | `true` | Write IMDb/TMDB/TVDB external-ID tags into the MKV (needs metadata providers). |
| `chapter_fallback_name` | str | `""` | Fallback template for chapter names, e.g. `"Chapter {i:02}"`. |
| `unicode_filenames` | bool | `false` | Allow Unicode in filenames; when `false`, names are ASCII-sanitised. |
| [`filename_replacements`](#filename_replacements) | dict | `{}` | Replace text in file and folder names, e.g. `&` with `and`. |
## `codec_names`
@@ -107,6 +108,34 @@ The `dl --export` file name does not use `codec_names`.
unshackle evaluates [`tag_rules`](#tag_rules) after the rename. With the example above, a
rule must match `audio: EAC3`, not `audio: DDP`.
## `filename_replacements`
- **Type:** `dict` &nbsp;·&nbsp; **Default:** `{}`
Replaces text in file and folder names. Each entry of the map names the text to find, and its
value is the text to write instead. An empty value removes the text. unshackle applies the map
in order, before it sanitises the name, so a later entry also sees the result of an earlier
entry. You can also set `filename_replacements` for one service under `services`.
```yaml title="unshackle.yaml"
filename_replacements:
"&": and # Tom & Jerry -> Tom.and.Jerry, Tom&Jerry -> Tom.and.Jerry
```
Put quotes around text such as `"&"`: YAML reads a bare `&` as an anchor. When the text to
find has no letters or digits and the replacement is a word, unshackle puts a separator on each
side of the replacement, so `Tom&Jerry` gives `Tom.and.Jerry`. The map also changes text
inside a word: `AT&T` gives `AT.and.T`. An entry that does not map text to text stops
unshackle at startup with an error.
The map applies to the whole name that a template makes, and also to the title part of the
`dl --export` file name. Find only text that titles contain: an entry for `-` also changes
`WEB-DL` and the `-{tag}` separator. The ` & ` that unshackle writes for `/` and `;` in a
multi-episode name stays as it is, unless the map has an entry for `/` or `;`.
unshackle finds the text before it transliterates the name to ASCII. For a title that uses a
variant of a character, such as the fullwidth `&`, add an entry for that variant too.
## `tag_rules`
- **Type:** `list` &nbsp;·&nbsp; **Default:** `[]`
+6
View File
@@ -70,6 +70,12 @@ def default_codec_names(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(config, "codec_names", {})
@pytest.fixture(autouse=True)
def no_filename_replacements(monkeypatch: pytest.MonkeyPatch) -> None:
"""Keep names as sanitize_filename makes them, whatever filename_replacements the local unshackle.yaml sets."""
monkeypatch.setattr(config, "filename_replacements", {})
@pytest.fixture(autouse=True)
def no_speed_limit(monkeypatch: pytest.MonkeyPatch) -> None:
"""Start with no speed limit, so a limit that an earlier test locked cannot block a later one."""
+51 -1
View File
@@ -11,7 +11,7 @@ from __future__ import annotations
import pytest
from unshackle.core.config import config
from unshackle.core.config import Config, config
from unshackle.core.utilities import sanitize_filename
THAI = "\u0e40\u0e1b\u0e47\u0e19\u0e15\u0e48\u0e2d" # a Thai title with vowel and tone marks
@@ -73,3 +73,53 @@ def test_sanitising_a_name_again_does_not_change_it() -> None:
once = sanitize_filename("e?\u0301", unicode=True)
assert once == "\u00e9"
assert sanitize_filename(once, unicode=True) == once
@pytest.mark.parametrize(
("mapping", "name", "spacer", "expected"),
[
({}, "Tom & Jerry", ".", "Tom.&.Jerry"),
({"&": "and"}, "Tom & Jerry", ".", "Tom.and.Jerry"),
({"&": "and"}, "Tom&Jerry", ".", "Tom.and.Jerry"),
({"&": "and"}, "Tom & Jerry", " ", "Tom and Jerry"),
({"&": "and"}, "Part 1/Part 2 & More", " ", "Part 1 & Part 2 and More"),
({"&": "and"}, "Part 1;Part 2", ".", "Part.1.&.Part.2"),
({"&": ""}, "Tom & Jerry", ".", "Tom.Jerry"),
({"\u00e4": "ae"}, "M\u00e4dchen", ".", "Maedchen"),
({"&": "and", "and": "plus"}, "Tom & Jerry", ".", "Tom.plus.Jerry"),
({"&": "+"}, "Tom&Jerry", ".", "Tom+Jerry"),
],
)
def test_filename_replacements_change_only_the_name_text(monkeypatch, mapping, name, spacer, expected) -> None:
monkeypatch.setattr(config, "filename_replacements", mapping)
assert sanitize_filename(name, spacer, unicode=True) == expected
def test_episode_folder_from_the_series_template_keeps_the_multi_episode_separator(monkeypatch) -> None:
from unshackle.core.titles.episode import Episode
class StubMediaInfo:
video_tracks: list = []
audio_tracks: list = []
monkeypatch.setattr(config, "filename_replacements", {"&": "and"})
monkeypatch.setattr(config, "folder_templates", {})
monkeypatch.setattr(config, "folder_template", "")
monkeypatch.setattr(config, "output_template", {"series": "{title}.{season_episode}"})
episode = Episode(id_="episode-0001", service=object, title="A/B & C", season=1, number=2, name="Pilot")
assert episode.get_filename(StubMediaInfo(), folder=True) == "A.&.B.and.C.S01"
assert episode.get_filename(StubMediaInfo()) == "A.&.B.and.C.S01E02"
@pytest.mark.parametrize("value", [["&"], [], "", False, {"&": None}, {"": "and"}, {1: "one"}, {"&": True}])
def test_a_bad_filename_replacements_value_is_an_error(value) -> None:
with pytest.raises(SystemExit, match="filename_replacements"):
Config(filename_replacements=value)
def test_filename_replacements_default_to_empty_and_use_nfc_keys(monkeypatch) -> None:
assert Config().filename_replacements == {}
monkeypatch.setattr(
config, "filename_replacements", Config(filename_replacements={"e\u0301": "e"}).filename_replacements
)
assert sanitize_filename("Caf\u00e9", unicode=True) == "Cafe"
+8 -1
View File
@@ -31,7 +31,13 @@ from rich.table import Table
from unshackle.core import __version__, binaries, login
from unshackle.core.cdm.choice import choose_cdm
from unshackle.core.cdm.detect import cdm_system, cdm_type_stub, is_playready_cdm, is_remote_cdm
from unshackle.core.config import cdm_entry_names_device, config, resolve_cdm_name, resolve_decryption
from unshackle.core.config import (
cdm_entry_names_device,
check_filename_replacements,
config,
resolve_cdm_name,
resolve_decryption,
)
from unshackle.core.console import SyncLive, console, listing_panel, print_listing
from unshackle.core.constants import (
DEFAULT_SAMPLE,
@@ -1330,6 +1336,7 @@ class dl:
self.log.debug(
f"Applied service-specific '{config_key}' overrides for {self.service}: {override_value}"
)
config.filename_replacements = check_filename_replacements(config.filename_replacements)
self.cdm_override = ctx.params.get("cdm_name")
cdm_only = ctx.params.get("cdm_only")
+13
View File
@@ -2,6 +2,7 @@ from __future__ import annotations
import logging
import re
import unicodedata
import warnings
from pathlib import Path
from typing import Any
@@ -62,6 +63,17 @@ def restore_bool_languages(data: Any) -> Any:
return fixed
def check_filename_replacements(value: Any) -> dict[str, str]:
"""The ``filename_replacements`` map with NFC keys; exits with one line when it does not map text to text."""
if value is None:
return {}
if not isinstance(value, dict) or not all(
isinstance(k, str) and k and isinstance(v, str) for k, v in value.items()
):
raise SystemExit(f"ERROR: filename_replacements must map text to text, not {value!r}")
return {unicodedata.normalize("NFC", k): v for k, v in value.items()}
def resolve_decryption(decryption_map: dict, default: str, service: str) -> str:
"""Pick the decryption backend for a service (case-insensitive), falling back to default."""
return ci_get(decryption_map, service, default)
@@ -229,6 +241,7 @@ class Config:
self.validate_output_templates()
self.unicode_filenames: bool = kwargs.get("unicode_filenames", False)
self.filename_replacements = check_filename_replacements(kwargs.get("filename_replacements"))
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
+1 -6
View File
@@ -256,17 +256,12 @@ class Episode(Title):
derived_template = re.sub(r"\s{2,}", " ", derived_template)
derived_template = re.sub(r"^[\.\s]+|[\.\s]+$", "", derived_template)
formatter = TemplateFormatter(derived_template)
context = self.build_template_context(media_info, show_service, include_part=False)
context["season"] = self.folder_season()
# folders keep the year, unless the season label is already the air year
context["year"] = "" if str(self.year) == context["season"] else self.year or ""
folder_name = formatter.format(context)
separators = re.sub(r"\{[^}]*\}", "", derived_template)
spacer = "." if "." in separators and " " not in separators else " "
return sanitize_filename(folder_name, spacer)
return TemplateFormatter(derived_template).format(context)
else:
name = f"{self.title}"
if self.year:
+5
View File
@@ -128,8 +128,13 @@ def sanitize_filename(filename: str, spacer: str = ".", unicode: bool | None = N
transliterating them to ASCII equivalents. Pass ``unicode`` to decide that
for one call instead of the config value. The name goes to NFC first, so
composed and decomposed spellings of a title give the same name.
`filename_replacements` in config replaces text first. A word that replaces text with no letters
or digits gets a space on each side, so it stays a separate word.
"""
filename = unicodedata.normalize("NFC", filename)
for old, new in config.filename_replacements.items():
word = any(c.isalnum() for c in new) and not any(c.isalnum() for c in old)
filename = filename.replace(old, f" {new} " if word else new)
if not (config.unicode_filenames if unicode is None else unicode):
filename = unidecode(filename)
filename = re.sub(r"\[\(+", "[", filename)