| 1 |
"""Apply NYT manual of style title case rules, to text. |
| 2 |
Title case logic is derived from the python-titlecase library. |
| 3 |
Provides a template function and a tag modification function.""" |
| 4 |
|
| 5 |
from __future__ import annotations |
| 6 |
|
| 7 |
import re |
| 8 |
from functools import cached_property |
| 9 |
from typing import TYPE_CHECKING, TypedDict |
| 10 |
|
| 11 |
from titlecase import titlecase |
| 12 |
|
| 13 |
from beets import ui |
| 14 |
from beets.autotag import AlbumInfo |
| 15 |
from beets.plugins import BeetsPlugin |
| 16 |
|
| 17 |
if TYPE_CHECKING: |
| 18 |
import optparse |
| 19 |
|
| 20 |
from beets.autotag import Info |
| 21 |
from beets.importer import ImportSession, ImportTask |
| 22 |
from beets.library import Item, Library |
| 23 |
|
| 24 |
__author__ = "[email protected]" |
| 25 |
__version__ = "1.0" |
| 26 |
|
| 27 |
|
| 28 |
class PreservedText(TypedDict): |
| 29 |
words: dict[str, str] |
| 30 |
phrases: dict[str, re.Pattern[str]] |
| 31 |
|
| 32 |
|
| 33 |
class TitlecasePlugin(BeetsPlugin): |
| 34 |
def __init__(self) -> None: |
| 35 |
super().__init__() |
| 36 |
|
| 37 |
self.config.add( |
| 38 |
{ |
| 39 |
"auto": True, |
| 40 |
"preserve": [], |
| 41 |
"fields": [], |
| 42 |
"replace": [], |
| 43 |
"separators": [], |
| 44 |
"force_lowercase": False, |
| 45 |
"small_first_last": True, |
| 46 |
"the_artist": True, |
| 47 |
"all_caps": False, |
| 48 |
"all_lowercase": False, |
| 49 |
"after_choice": False, |
| 50 |
} |
| 51 |
) |
| 52 |
|
| 53 |
""" |
| 54 |
auto - Automatically apply titlecase to new import metadata. |
| 55 |
preserve - Provide a list of strings with specific case requirements. |
| 56 |
fields - Fields to apply titlecase to. |
| 57 |
replace - List of pairs, first is the target, second is the replacement |
| 58 |
separators - Other characters to treat like periods. |
| 59 |
force_lowercase - Lowercase the string before titlecase. |
| 60 |
small_first_last - If small characters should be cased at the start of strings. |
| 61 |
the_artist - If the plugin infers the field to be an artist field |
| 62 |
(e.g. the field contains "artist") |
| 63 |
It will capitalize a lowercase The, helpful for the artist names |
| 64 |
that start with 'The', like 'The Who' or 'The Talking Heads' when |
| 65 |
they are not at the start of a string. Superseded by preserved phrases. |
| 66 |
all_caps - If the alphabet in the string is all uppercase, do not modify. |
| 67 |
all_lowercase - If the alphabet in the string is all lowercase, do not modify. |
| 68 |
""" |
| 69 |
# Register template function |
| 70 |
self.template_funcs["titlecase"] = self.titlecase |
| 71 |
|
| 72 |
# Register UI subcommands |
| 73 |
self._command = ui.Subcommand( |
| 74 |
"titlecase", |
| 75 |
help="Apply titlecasing to metadata specified in config.", |
| 76 |
) |
| 77 |
|
| 78 |
if self.config["auto"].get(bool): |
| 79 |
if self.config["after_choice"].get(bool): |
| 80 |
self.import_stages = [self.imported] |
| 81 |
else: |
| 82 |
self.register_listener( |
| 83 |
"trackinfo_received", self.received_info_handler |
| 84 |
) |
| 85 |
self.register_listener( |
| 86 |
"albuminfo_received", self.received_info_handler |
| 87 |
) |
| 88 |
|
| 89 |
@cached_property |
| 90 |
def force_lowercase(self) -> bool: |
| 91 |
return self.config["force_lowercase"].get(bool) |
| 92 |
|
| 93 |
@cached_property |
| 94 |
def replace(self) -> list[tuple[str, str]]: |
| 95 |
return self.config["replace"].as_pairs(default_value="") |
| 96 |
|
| 97 |
@cached_property |
| 98 |
def the_artist(self) -> bool: |
| 99 |
return self.config["the_artist"].get(bool) |
| 100 |
|
| 101 |
@cached_property |
| 102 |
def fields_to_process(self) -> set[str]: |
| 103 |
fields = set(self.config["fields"].as_str_seq()) |
| 104 |
self._log.debug(f"fields: {', '.join(fields)}") |
| 105 |
return fields |
| 106 |
|
| 107 |
@cached_property |
| 108 |
def preserve(self) -> PreservedText: |
| 109 |
strings = self.config["preserve"].as_str_seq() |
| 110 |
preserved: PreservedText = {"words": {}, "phrases": {}} |
| 111 |
for s in strings: |
| 112 |
if " " in s: |
| 113 |
preserved["phrases"][s] = re.compile( |
| 114 |
rf"\b{re.escape(s)}\b", re.IGNORECASE |
| 115 |
) |
| 116 |
else: |
| 117 |
preserved["words"][s.upper()] = s |
| 118 |
return preserved |
| 119 |
|
| 120 |
@cached_property |
| 121 |
def separators(self) -> re.Pattern[str] | None: |
| 122 |
if separators := "".join( |
| 123 |
dict.fromkeys(self.config["separators"].as_str_seq()) |
| 124 |
): |
| 125 |
return re.compile(rf"(.*?[{re.escape(separators)}]+)(\s*)(?=.)") |
| 126 |
return None |
| 127 |
|
| 128 |
@cached_property |
| 129 |
def small_first_last(self) -> bool: |
| 130 |
return self.config["small_first_last"].get(bool) |
| 131 |
|
| 132 |
@cached_property |
| 133 |
def all_caps(self) -> bool: |
| 134 |
return self.config["all_caps"].get(bool) |
| 135 |
|
| 136 |
@cached_property |
| 137 |
def all_lowercase(self) -> bool: |
| 138 |
return self.config["all_lowercase"].get(bool) |
| 139 |
|
| 140 |
@cached_property |
| 141 |
def the_artist_regexp(self) -> re.Pattern[str]: |
| 142 |
return re.compile(r"\bthe\b") |
| 143 |
|
| 144 |
def titlecase_callback(self, word: str, **kwargs) -> str | None: |
| 145 |
"""Callback function for words to preserve case of.""" |
| 146 |
if preserved_word := self.preserve["words"].get(word.upper(), ""): |
| 147 |
return preserved_word |
| 148 |
return None |
| 149 |
|
| 150 |
def received_info_handler(self, info: Info) -> None: |
| 151 |
"""Calls titlecase fields for AlbumInfo or TrackInfo |
| 152 |
Processes the tracks field for AlbumInfo |
| 153 |
""" |
| 154 |
self.titlecase_fields(info) |
| 155 |
if isinstance(info, AlbumInfo): |
| 156 |
for track in info.tracks: |
| 157 |
self.titlecase_fields(track) |
| 158 |
|
| 159 |
def commands(self) -> list[ui.Subcommand]: |
| 160 |
def func(lib: Library, opts: optparse.Values, args: list[str]) -> None: |
| 161 |
write = ui.should_write() |
| 162 |
for item in lib.items(args): |
| 163 |
self._log.info(f"titlecasing {item.title}:") |
| 164 |
self.titlecase_fields(item) |
| 165 |
item.store() |
| 166 |
if write: |
| 167 |
item.try_write() |
| 168 |
|
| 169 |
self._command.func = func |
| 170 |
return [self._command] |
| 171 |
|
| 172 |
def titlecase_fields(self, item: Item | Info) -> None: |
| 173 |
"""Applies titlecase to fields, except |
| 174 |
those excluded by the default exclusions and the |
| 175 |
set exclude lists. |
| 176 |
""" |
| 177 |
for field in self.fields_to_process: |
| 178 |
init_field = getattr(item, field, "") |
| 179 |
if init_field: |
| 180 |
if isinstance(init_field, list) and isinstance( |
| 181 |
init_field[0], str |
| 182 |
): |
| 183 |
cased_list: list[str] = [ |
| 184 |
self.titlecase(i, field) for i in init_field |
| 185 |
] |
| 186 |
if cased_list != init_field: |
| 187 |
setattr(item, field, cased_list) |
| 188 |
self._log.debug( |
| 189 |
f"{field}: {', '.join(init_field)} ->", |
| 190 |
f"{', '.join(cased_list)}", |
| 191 |
) |
| 192 |
elif isinstance(init_field, str): |
| 193 |
cased: str = self.titlecase(init_field, field) |
| 194 |
if cased != init_field: |
| 195 |
setattr(item, field, cased) |
| 196 |
self._log.debug(f"{field}: {init_field} -> {cased}") |
| 197 |
else: |
| 198 |
self._log.debug(f"{field}: no string present") |
| 199 |
else: |
| 200 |
self._log.debug(f"{field}: does not exist on {type(item)}") |
| 201 |
|
| 202 |
def titlecase(self, text: str, field: str = "") -> str: |
| 203 |
"""Titlecase the given text.""" |
| 204 |
# Check we should split this into two substrings. |
| 205 |
if self.separators: |
| 206 |
if len(splits := self.separators.findall(text)): |
| 207 |
split_cased = "".join( |
| 208 |
[self.titlecase(s[0], field) + s[1] for s in splits] |
| 209 |
) |
| 210 |
# Add on the remaining portion |
| 211 |
return split_cased + self.titlecase( |
| 212 |
text[len(split_cased) :], field |
| 213 |
) |
| 214 |
# Check if A-Z is all uppercase or all lowercase |
| 215 |
if self.all_lowercase and text.islower(): |
| 216 |
return text |
| 217 |
if self.all_caps and text.isupper(): |
| 218 |
return text |
| 219 |
# Any necessary replacements go first, mainly punctuation. |
| 220 |
titlecased = text.lower() if self.force_lowercase else text |
| 221 |
for pair in self.replace: |
| 222 |
target, replacement = pair |
| 223 |
titlecased = titlecased.replace(target, replacement) |
| 224 |
# General titlecase operation |
| 225 |
titlecased = titlecase( |
| 226 |
titlecased, |
| 227 |
small_first_last=self.small_first_last, |
| 228 |
callback=self.titlecase_callback, |
| 229 |
) |
| 230 |
# Apply "The Artist" feature |
| 231 |
if self.the_artist and "artist" in field: |
| 232 |
titlecased = self.the_artist_regexp.sub("The", titlecased) |
| 233 |
# More complicated phrase replacements. |
| 234 |
for phrase, regexp in self.preserve["phrases"].items(): |
| 235 |
titlecased = regexp.sub(phrase, titlecased) |
| 236 |
return titlecased |
| 237 |
|
| 238 |
def imported(self, session: ImportSession, task: ImportTask) -> None: |
| 239 |
"""Import hook for titlecasing on import.""" |
| 240 |
for item in task.imported_items(): |
| 241 |
try: |
| 242 |
self._log.debug(f"titlecasing {item.title}:") |
| 243 |
self.titlecase_fields(item) |
| 244 |
item.store() |
| 245 |
except Exception as e: |
| 246 |
self._log.debug(f"titlecasing exception {e}") |