| 1 |
"""Provides the %bucket{} function for path formatting.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import re |
| 6 |
import string |
| 7 |
from datetime import datetime |
| 8 |
from itertools import tee |
| 9 |
from typing import TYPE_CHECKING, TypedDict, TypeVar |
| 10 |
|
| 11 |
from beets import plugins |
| 12 |
from beets.exceptions import UserError |
| 13 |
|
| 14 |
if TYPE_CHECKING: |
| 15 |
from collections.abc import Callable, Iterable, Iterator |
| 16 |
|
| 17 |
ASCII_DIGITS = string.digits + string.ascii_lowercase |
| 18 |
T = TypeVar("T") |
| 19 |
YearSpan = TypedDict( |
| 20 |
"YearSpan", {"from": int, "to": int, "str": str}, total=False |
| 21 |
) |
| 22 |
|
| 23 |
|
| 24 |
class SpanFormat(TypedDict): |
| 25 |
fromnchars: int |
| 26 |
tonchars: int |
| 27 |
fmt: str |
| 28 |
|
| 29 |
|
| 30 |
class BucketError(Exception): |
| 31 |
pass |
| 32 |
|
| 33 |
|
| 34 |
def pairwise(iterable: Iterable[T]) -> Iterator[tuple[T, T]]: |
| 35 |
"s -> (s0,s1), (s1,s2), (s2, s3), ..." |
| 36 |
a, b = tee(iterable) |
| 37 |
next(b, None) |
| 38 |
return zip(a, b) |
| 39 |
|
| 40 |
|
| 41 |
def span_from_str(span_str: str) -> YearSpan: |
| 42 |
"""Build a span dict from the span string representation.""" |
| 43 |
|
| 44 |
def normalize_year(d: int, yearfrom: int) -> int: |
| 45 |
"""Convert string to a 4 digits year""" |
| 46 |
if yearfrom < 100: |
| 47 |
raise BucketError(f"{yearfrom} must be expressed on 4 digits") |
| 48 |
|
| 49 |
# if two digits only, pick closest year that ends by these two |
| 50 |
# digits starting from yearfrom |
| 51 |
if d < 100: |
| 52 |
if (d % 100) < (yearfrom % 100): |
| 53 |
d = (yearfrom - yearfrom % 100) + 100 + d |
| 54 |
else: |
| 55 |
d = (yearfrom - yearfrom % 100) + d |
| 56 |
return d |
| 57 |
|
| 58 |
years = [int(x) for x in re.findall(r"\d+", span_str)] |
| 59 |
if not years: |
| 60 |
raise UserError( |
| 61 |
f"invalid range defined for year bucket {span_str!r}: no year found" |
| 62 |
) |
| 63 |
try: |
| 64 |
years = [normalize_year(x, years[0]) for x in years] |
| 65 |
except BucketError as exc: |
| 66 |
raise UserError( |
| 67 |
f"invalid range defined for year bucket {span_str!r}: {exc}" |
| 68 |
) |
| 69 |
|
| 70 |
res: YearSpan = {"from": years[0], "str": span_str} |
| 71 |
if len(years) > 1: |
| 72 |
res["to"] = years[-1] |
| 73 |
return res |
| 74 |
|
| 75 |
|
| 76 |
def complete_year_spans(spans: list[YearSpan]) -> None: |
| 77 |
"""Set the `to` value of spans if empty and sort them chronologically.""" |
| 78 |
spans.sort(key=lambda x: x["from"]) |
| 79 |
for x, y in pairwise(spans): |
| 80 |
if "to" not in x: |
| 81 |
x["to"] = y["from"] - 1 |
| 82 |
if spans and "to" not in spans[-1]: |
| 83 |
spans[-1]["to"] = datetime.now().year |
| 84 |
|
| 85 |
|
| 86 |
def extend_year_spans( |
| 87 |
spans: list[YearSpan], spanlen: int, start: int = 1900, end: int = 2014 |
| 88 |
) -> list[YearSpan]: |
| 89 |
"""Add new spans to given spans list so that every year of [start,end] |
| 90 |
belongs to a span. |
| 91 |
""" |
| 92 |
extended_spans = spans[:] |
| 93 |
for x, y in pairwise(spans): |
| 94 |
# if a gap between two spans, fill the gap with as much spans of |
| 95 |
# spanlen length as necessary |
| 96 |
for span_from in range(x["to"] + 1, y["from"], spanlen): |
| 97 |
extended_spans.append({"from": span_from}) |
| 98 |
# Create spans prior to declared ones |
| 99 |
for span_from in range(spans[0]["from"] - spanlen, start, -spanlen): |
| 100 |
extended_spans.append({"from": span_from}) |
| 101 |
# Create spans after the declared ones |
| 102 |
for span_from in range(spans[-1]["to"] + 1, end, spanlen): |
| 103 |
extended_spans.append({"from": span_from}) |
| 104 |
|
| 105 |
complete_year_spans(extended_spans) |
| 106 |
return extended_spans |
| 107 |
|
| 108 |
|
| 109 |
def build_year_spans(year_spans_str: Iterable[str]) -> list[YearSpan]: |
| 110 |
"""Build a chronologically ordered list of spans dict from unordered spans |
| 111 |
stringlist. |
| 112 |
""" |
| 113 |
spans = [] |
| 114 |
for elem in year_spans_str: |
| 115 |
spans.append(span_from_str(elem)) |
| 116 |
complete_year_spans(spans) |
| 117 |
return spans |
| 118 |
|
| 119 |
|
| 120 |
def str2fmt(s: str) -> SpanFormat: |
| 121 |
"""Deduces formatting syntax from a span string.""" |
| 122 |
regex = re.compile( |
| 123 |
r"(?P<bef>\D*)(?P<fromyear>\d+)(?P<sep>\D*)" |
| 124 |
r"(?P<toyear>\d*)(?P<after>\D*)" |
| 125 |
) |
| 126 |
m = re.match(regex, s) |
| 127 |
|
| 128 |
if m: |
| 129 |
fromnchars = len(m.group("fromyear")) |
| 130 |
tonchars = len(m.group("toyear")) |
| 131 |
fmt = f"{m['bef']}{{}}{m['sep']}{'{}' if tonchars else ''}{m['after']}" |
| 132 |
else: |
| 133 |
fromnchars = tonchars = 0 |
| 134 |
fmt = "{}" |
| 135 |
|
| 136 |
return {"fromnchars": fromnchars, "tonchars": tonchars, "fmt": fmt} |
| 137 |
|
| 138 |
|
| 139 |
def format_span( |
| 140 |
fmt: str, yearfrom: int, yearto: int, fromnchars: int, tonchars: int |
| 141 |
) -> str: |
| 142 |
"""Return a span string representation.""" |
| 143 |
args = [str(yearfrom)[-fromnchars:]] |
| 144 |
if tonchars: |
| 145 |
args.append(str(yearto)[-tonchars:]) |
| 146 |
|
| 147 |
return fmt.format(*args) |
| 148 |
|
| 149 |
|
| 150 |
def extract_modes(spans: Iterable[YearSpan]) -> tuple[int, SpanFormat]: |
| 151 |
"""Extract the most common spans lengths and representation formats""" |
| 152 |
rangelen = sorted([x["to"] - x["from"] + 1 for x in spans]) |
| 153 |
deflen = sorted(rangelen, key=rangelen.count)[-1] |
| 154 |
reprs = [str2fmt(x["str"]) for x in spans] |
| 155 |
deffmt = sorted(reprs, key=reprs.count)[-1] |
| 156 |
return deflen, deffmt |
| 157 |
|
| 158 |
|
| 159 |
def build_alpha_spans( |
| 160 |
alpha_spans_str: Iterable[str], alpha_regexs: dict[str, str] |
| 161 |
) -> list[re.Pattern[str]]: |
| 162 |
"""Extract alphanumerics from string and return sorted list of chars |
| 163 |
[from...to] |
| 164 |
""" |
| 165 |
spans = [] |
| 166 |
|
| 167 |
for elem in alpha_spans_str: |
| 168 |
if elem in alpha_regexs: |
| 169 |
spans.append(re.compile(alpha_regexs[elem])) |
| 170 |
else: |
| 171 |
bucket = sorted([x for x in elem.lower() if x.isalnum()]) |
| 172 |
if bucket: |
| 173 |
begin_index = ASCII_DIGITS.index(bucket[0]) |
| 174 |
end_index = ASCII_DIGITS.index(bucket[-1]) |
| 175 |
else: |
| 176 |
raise UserError( |
| 177 |
"invalid range defined for alpha bucket " |
| 178 |
f"'{elem}': no alphanumeric character found" |
| 179 |
) |
| 180 |
spans.append( |
| 181 |
re.compile( |
| 182 |
rf"^[{ASCII_DIGITS[begin_index : end_index + 1]}]", |
| 183 |
re.IGNORECASE, |
| 184 |
) |
| 185 |
) |
| 186 |
return spans |
| 187 |
|
| 188 |
|
| 189 |
class BucketPlugin(plugins.BeetsPlugin): |
| 190 |
def __init__(self) -> None: |
| 191 |
super().__init__() |
| 192 |
self.template_funcs["bucket"] = self._tmpl_bucket |
| 193 |
|
| 194 |
self.config.add( |
| 195 |
{ |
| 196 |
"bucket_year": [], |
| 197 |
"bucket_alpha": [], |
| 198 |
"bucket_alpha_regex": {}, |
| 199 |
"extrapolate": False, |
| 200 |
} |
| 201 |
) |
| 202 |
self.setup() |
| 203 |
|
| 204 |
def setup(self) -> None: |
| 205 |
"""Setup plugin from config options""" |
| 206 |
self.year_spans = build_year_spans(self.config["bucket_year"].get()) |
| 207 |
if self.year_spans and self.config["extrapolate"]: |
| 208 |
[self.ys_len_mode, self.ys_repr_mode] = extract_modes( |
| 209 |
self.year_spans |
| 210 |
) |
| 211 |
self.year_spans = extend_year_spans( |
| 212 |
self.year_spans, self.ys_len_mode |
| 213 |
) |
| 214 |
|
| 215 |
self.alpha_spans = build_alpha_spans( |
| 216 |
self.config["bucket_alpha"].get(), |
| 217 |
self.config["bucket_alpha_regex"].get(), |
| 218 |
) |
| 219 |
|
| 220 |
def find_bucket_year(self, year: str) -> str: |
| 221 |
"""Return bucket that matches given year or return the year |
| 222 |
if no matching bucket. |
| 223 |
""" |
| 224 |
for ys in self.year_spans: |
| 225 |
if ys["from"] <= int(year) <= ys["to"]: |
| 226 |
if "str" in ys: |
| 227 |
return ys["str"] |
| 228 |
return format_span( |
| 229 |
self.ys_repr_mode["fmt"], |
| 230 |
ys["from"], |
| 231 |
ys["to"], |
| 232 |
self.ys_repr_mode["fromnchars"], |
| 233 |
self.ys_repr_mode["tonchars"], |
| 234 |
) |
| 235 |
return year |
| 236 |
|
| 237 |
def find_bucket_alpha(self, s: str) -> str: |
| 238 |
"""Return alpha-range bucket that matches given string or return the |
| 239 |
string initial if no matching bucket. |
| 240 |
""" |
| 241 |
for i, span in enumerate(self.alpha_spans): |
| 242 |
if span.match(s): |
| 243 |
return self.config["bucket_alpha"].get()[i] |
| 244 |
return s[0].upper() |
| 245 |
|
| 246 |
def _tmpl_bucket(self, text: str, field: str | None = None) -> str: |
| 247 |
if not field and len(text) == 4 and text.isdigit(): |
| 248 |
field = "year" |
| 249 |
|
| 250 |
func: Callable[[str], str] |
| 251 |
if field == "year": |
| 252 |
func = self.find_bucket_year |
| 253 |
else: |
| 254 |
func = self.find_bucket_alpha |
| 255 |
return func(text) |