codetta 0.8.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- codetta/CHANGELOG.md +153 -0
- codetta/__init__.py +8 -0
- codetta/__main__.py +5 -0
- codetta/cli/__init__.py +0 -0
- codetta/cli/__main__.py +59 -0
- codetta/cli/run.py +129 -0
- codetta/core/__init__.py +0 -0
- codetta/core/acoustid.py +225 -0
- codetta/core/activity.py +161 -0
- codetta/core/artwork.py +238 -0
- codetta/core/auth.py +362 -0
- codetta/core/avatar.py +92 -0
- codetta/core/changelog.py +51 -0
- codetta/core/connections.py +159 -0
- codetta/core/describe.py +69 -0
- codetta/core/engine.py +470 -0
- codetta/core/health.py +520 -0
- codetta/core/inbox.py +195 -0
- codetta/core/index.py +672 -0
- codetta/core/library.py +177 -0
- codetta/core/musicbrainz.py +662 -0
- codetta/core/notifications.py +77 -0
- codetta/core/onboarding.py +39 -0
- codetta/core/organize.py +490 -0
- codetta/core/plugins.py +183 -0
- codetta/core/presets.py +452 -0
- codetta/core/providers.py +203 -0
- codetta/core/rawtags.py +135 -0
- codetta/core/slskd.py +650 -0
- codetta/core/tagmap.py +538 -0
- codetta/core/undo.py +186 -0
- codetta/core/updates.py +132 -0
- codetta/plugins/__init__.py +63 -0
- codetta/plugins/builtin/__init__.py +3 -0
- codetta/plugins/builtin/tidy.py +70 -0
- codetta/web/__init__.py +0 -0
- codetta/web/app.py +2909 -0
- codetta/web/security.py +170 -0
- codetta/web/static/app.css +2684 -0
- codetta/web/static/app.js +5694 -0
- codetta/web/static/apple-touch-icon.png +0 -0
- codetta/web/static/fonts/LICENSE-Inter.txt +93 -0
- codetta/web/static/fonts/LICENSE-SchibstedGrotesk.txt +93 -0
- codetta/web/static/fonts/inter-cyrillic.woff2 +0 -0
- codetta/web/static/fonts/schibsted-grotesk.woff2 +0 -0
- codetta/web/static/icon.svg +1 -0
- codetta/web/static/icons/codetta-dark.png +0 -0
- codetta/web/static/icons/codetta-dark.svg +1 -0
- codetta/web/static/icons/codetta-dark.webp +0 -0
- codetta/web/static/icons/codetta-light.png +0 -0
- codetta/web/static/icons/codetta-light.svg +1 -0
- codetta/web/static/icons/codetta-light.webp +0 -0
- codetta/web/static/icons/codetta.png +0 -0
- codetta/web/static/icons/codetta.svg +1 -0
- codetta/web/static/icons/codetta.webp +0 -0
- codetta/web/static/index.html +473 -0
- codetta/web/static/theme.js +12 -0
- codetta-0.8.1.dist-info/METADATA +282 -0
- codetta-0.8.1.dist-info/RECORD +63 -0
- codetta-0.8.1.dist-info/WHEEL +5 -0
- codetta-0.8.1.dist-info/entry_points.txt +2 -0
- codetta-0.8.1.dist-info/licenses/LICENSE +661 -0
- codetta-0.8.1.dist-info/top_level.txt +1 -0
codetta/core/undo.py
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
"""Undo for changes recorded in the activity log.
|
|
2
|
+
|
|
3
|
+
Every change Codetta makes is logged with an ``undo`` record holding, per
|
|
4
|
+
file, the exact values before and after the change:
|
|
5
|
+
|
|
6
|
+
{"type": "tags", "files": {"Artist/Album/01.flac": {"before": {"genre": ["Rock"]},
|
|
7
|
+
"after": {"genre": ["Jazz"]}}}}
|
|
8
|
+
{"type": "art", "files": {"Artist/Album/01.flac": {"before": "<sha256 or null>",
|
|
9
|
+
"after": "<sha256 or null>"}}}
|
|
10
|
+
|
|
11
|
+
{"type": "multi", "parts": [<tags record>, <art record>]} (e.g. a MusicBrainz match)
|
|
12
|
+
{"type": "moves", "moves": [["old/path.flac", "new/path.flac"], ...]} (Organize)
|
|
13
|
+
|
|
14
|
+
Album art is too big for the log, so images are kept in an ``ArtStore``
|
|
15
|
+
(one file per distinct image, so a cover shared by a whole album is stored
|
|
16
|
+
once) and the log only holds their SHA-256.
|
|
17
|
+
|
|
18
|
+
Undoing only touches files that still have the "after" values. A file that
|
|
19
|
+
was edited again since is skipped and reported, so undo never overwrites a
|
|
20
|
+
newer change. Undo produces its own undo record (before/after swapped), so
|
|
21
|
+
an undo can itself be undone.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
import hashlib
|
|
27
|
+
import os
|
|
28
|
+
import tempfile
|
|
29
|
+
from collections.abc import Callable, Iterable
|
|
30
|
+
from dataclasses import dataclass, field
|
|
31
|
+
from pathlib import Path
|
|
32
|
+
|
|
33
|
+
from codetta.core.engine import MetadataEngine, MetadataError
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def sha256(data: bytes) -> str:
|
|
37
|
+
return hashlib.sha256(data).hexdigest()
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class ArtStore:
|
|
41
|
+
"""Previous album-art images, stored by content hash in the config folder."""
|
|
42
|
+
|
|
43
|
+
def __init__(self, directory: Path) -> None:
|
|
44
|
+
self.directory = directory
|
|
45
|
+
|
|
46
|
+
def save(self, data: bytes | None) -> str | None:
|
|
47
|
+
if data is None:
|
|
48
|
+
return None
|
|
49
|
+
digest = sha256(data)
|
|
50
|
+
path = self.directory / digest
|
|
51
|
+
if not path.exists():
|
|
52
|
+
self.directory.mkdir(parents=True, exist_ok=True)
|
|
53
|
+
fd, tmp = tempfile.mkstemp(prefix=".codetta-", dir=self.directory)
|
|
54
|
+
with os.fdopen(fd, "wb") as f:
|
|
55
|
+
f.write(data)
|
|
56
|
+
os.replace(tmp, path)
|
|
57
|
+
return digest
|
|
58
|
+
|
|
59
|
+
def load(self, digest: str | None) -> bytes | None:
|
|
60
|
+
if digest is None:
|
|
61
|
+
return None
|
|
62
|
+
try:
|
|
63
|
+
return (self.directory / digest).read_bytes()
|
|
64
|
+
except OSError as exc:
|
|
65
|
+
raise MetadataError("The saved album art for this change is no longer available") from exc
|
|
66
|
+
|
|
67
|
+
def prune(self, keep: Iterable[str]) -> None:
|
|
68
|
+
"""Delete stored images no longer referenced by the activity log."""
|
|
69
|
+
if not self.directory.is_dir():
|
|
70
|
+
return
|
|
71
|
+
keep = set(keep)
|
|
72
|
+
for path in self.directory.iterdir():
|
|
73
|
+
if path.is_file() and not path.name.startswith(".") and path.name not in keep:
|
|
74
|
+
path.unlink(missing_ok=True)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def art_hashes(undo: dict | None) -> set[str]:
|
|
78
|
+
"""Image hashes an undo record refers to (for pruning the ArtStore)."""
|
|
79
|
+
if undo and undo.get("type") == "multi":
|
|
80
|
+
return {h for part in undo.get("parts", []) for h in art_hashes(part)}
|
|
81
|
+
if not undo or undo.get("type") != "art":
|
|
82
|
+
return set()
|
|
83
|
+
return {h for f in undo["files"].values() for h in (f.get("before"), f.get("after")) if h}
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
@dataclass
|
|
87
|
+
class UndoResult:
|
|
88
|
+
path: str
|
|
89
|
+
ok: bool
|
|
90
|
+
skipped: bool = False # changed since; left alone on purpose
|
|
91
|
+
error: str | None = None
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
@dataclass
|
|
95
|
+
class UndoOutcome:
|
|
96
|
+
results: list[UndoResult] = field(default_factory=list)
|
|
97
|
+
reverse: dict | None = None # undo record for this undo (i.e. redo)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def undo_change(
|
|
101
|
+
engine: MetadataEngine,
|
|
102
|
+
resolve: Callable[[str], Path],
|
|
103
|
+
art: ArtStore,
|
|
104
|
+
record: dict,
|
|
105
|
+
) -> UndoOutcome:
|
|
106
|
+
"""Put each file in ``record`` back to its "before" state, where safe."""
|
|
107
|
+
kind = record.get("type")
|
|
108
|
+
if kind == "multi":
|
|
109
|
+
return _undo_multi(engine, resolve, art, record)
|
|
110
|
+
if kind == "moves":
|
|
111
|
+
return _undo_moves(resolve, record)
|
|
112
|
+
outcome = UndoOutcome()
|
|
113
|
+
reverse_files: dict[str, dict] = {}
|
|
114
|
+
|
|
115
|
+
for rel, change in record.get("files", {}).items():
|
|
116
|
+
try:
|
|
117
|
+
target = resolve(rel)
|
|
118
|
+
if kind == "tags":
|
|
119
|
+
current = engine.load_metadata(target).tags
|
|
120
|
+
if any(current.get(k, []) != v for k, v in change["after"].items()):
|
|
121
|
+
outcome.results.append(UndoResult(rel, ok=False, skipped=True,
|
|
122
|
+
error="Changed since, so it was left as it is"))
|
|
123
|
+
continue
|
|
124
|
+
engine.update_tags(target, {k: (v or None) for k, v in change["before"].items()})
|
|
125
|
+
reverse_files[rel] = {"before": change["after"], "after": change["before"]}
|
|
126
|
+
elif kind == "art":
|
|
127
|
+
now = engine.read_artwork(target)
|
|
128
|
+
if (sha256(now.data) if now else None) != change["after"]:
|
|
129
|
+
outcome.results.append(UndoResult(rel, ok=False, skipped=True,
|
|
130
|
+
error="Album art changed since, so it was left as it is"))
|
|
131
|
+
continue
|
|
132
|
+
engine.update_artwork(target, art.load(change["before"]))
|
|
133
|
+
reverse_files[rel] = {"before": change["after"], "after": change["before"]}
|
|
134
|
+
else:
|
|
135
|
+
outcome.results.append(UndoResult(rel, ok=False, error="Unknown change type"))
|
|
136
|
+
continue
|
|
137
|
+
outcome.results.append(UndoResult(rel, ok=True))
|
|
138
|
+
except (MetadataError, OSError, ValueError) as exc:
|
|
139
|
+
outcome.results.append(UndoResult(rel, ok=False, error=str(exc)))
|
|
140
|
+
|
|
141
|
+
if reverse_files:
|
|
142
|
+
outcome.reverse = {"type": kind, "files": reverse_files}
|
|
143
|
+
return outcome
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _undo_multi(engine: MetadataEngine, resolve: Callable[[str], Path], art: ArtStore, record: dict) -> UndoOutcome:
|
|
147
|
+
"""Undo each part (tags, then art) and report one result per file: done if
|
|
148
|
+
any part of it could be put back, skipped if every part changed since."""
|
|
149
|
+
parts = [undo_change(engine, resolve, art, p) for p in record.get("parts", []) if isinstance(p, dict)]
|
|
150
|
+
by_path: dict[str, list[UndoResult]] = {}
|
|
151
|
+
for part in parts:
|
|
152
|
+
for r in part.results:
|
|
153
|
+
by_path.setdefault(r.path, []).append(r)
|
|
154
|
+
outcome = UndoOutcome()
|
|
155
|
+
for path, rs in by_path.items():
|
|
156
|
+
if any(r.ok for r in rs):
|
|
157
|
+
outcome.results.append(UndoResult(path, ok=True))
|
|
158
|
+
else:
|
|
159
|
+
skipped = all(r.skipped for r in rs)
|
|
160
|
+
outcome.results.append(UndoResult(path, ok=False, skipped=skipped, error=next((r.error for r in rs if r.error), None)))
|
|
161
|
+
reverse = [p.reverse for p in parts if p.reverse]
|
|
162
|
+
if reverse:
|
|
163
|
+
outcome.reverse = {"type": "multi", "parts": reverse}
|
|
164
|
+
return outcome
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _undo_moves(resolve: Callable[[str], Path], record: dict) -> UndoOutcome:
|
|
168
|
+
"""Move organized files back to where they were."""
|
|
169
|
+
from codetta.core.organize import undo_moves
|
|
170
|
+
|
|
171
|
+
moves = [m for m in record.get("moves", []) if isinstance(m, list) and len(m) == 2]
|
|
172
|
+
for src, dst in moves: # validate every path before touching anything
|
|
173
|
+
resolve(src)
|
|
174
|
+
resolve(dst)
|
|
175
|
+
report, reverse = undo_moves(resolve, moves)
|
|
176
|
+
outcome = UndoOutcome()
|
|
177
|
+
from codetta.core.engine import SUPPORTED_EXTENSIONS
|
|
178
|
+
|
|
179
|
+
audio = {src for src, _ in moves if Path(src).suffix.lower() in SUPPORTED_EXTENSIONS} # report per song
|
|
180
|
+
for src, dst, ok, error in report:
|
|
181
|
+
if src in audio or not ok:
|
|
182
|
+
skipped = not ok and error is not None and "left alone" in error
|
|
183
|
+
outcome.results.append(UndoResult(dst, ok=ok, skipped=skipped, error=error))
|
|
184
|
+
if reverse:
|
|
185
|
+
outcome.reverse = {"type": "moves", "moves": reverse}
|
|
186
|
+
return outcome
|
codetta/core/updates.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
"""Is a newer Codetta release available?
|
|
2
|
+
|
|
3
|
+
The server asks GitHub for the latest published release of the Codetta repo,
|
|
4
|
+
at most every ``ttl`` seconds, and compares version numbers. The request
|
|
5
|
+
carries no information about you or your library (just a generic
|
|
6
|
+
User-Agent), and only when the "Update check" connection is on (see
|
|
7
|
+
``connections.py``; ``CODETTA_UPDATE_CHECK=on|off`` sets it).
|
|
8
|
+
|
|
9
|
+
Codetta never updates itself: doing that from inside a container would need
|
|
10
|
+
control of Docker, which means control of the whole server. Instead the UI
|
|
11
|
+
shows what's new and the commands to update.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import json
|
|
17
|
+
import re
|
|
18
|
+
import threading
|
|
19
|
+
import time
|
|
20
|
+
import urllib.error
|
|
21
|
+
import urllib.request
|
|
22
|
+
from collections.abc import Callable
|
|
23
|
+
|
|
24
|
+
DEFAULT_REPO = "gavndev/codetta"
|
|
25
|
+
CHECK_EVERY = 12 * 3600 # seconds
|
|
26
|
+
|
|
27
|
+
# fetch(repo) -> {"tag_name", "html_url", "body", "published_at"} or raises
|
|
28
|
+
Fetcher = Callable[[str], dict]
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def parse_version(text: str | None) -> tuple[int, ...] | None:
|
|
32
|
+
""" "v0.10.2" -> (0, 10, 2). Pre-release suffixes ("-beta") are ignored."""
|
|
33
|
+
if not text:
|
|
34
|
+
return None
|
|
35
|
+
m = re.match(r"^\s*v?(\d+(?:\.\d+)*)", text)
|
|
36
|
+
return tuple(int(p) for p in m.group(1).split(".")) if m else None
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def is_newer(candidate: str | None, current: str | None) -> bool:
|
|
40
|
+
a, b = parse_version(candidate), parse_version(current)
|
|
41
|
+
if a is None or b is None:
|
|
42
|
+
return False
|
|
43
|
+
width = max(len(a), len(b))
|
|
44
|
+
return a + (0,) * (width - len(a)) > b + (0,) * (width - len(b))
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
_REPO_RE = re.compile(r"^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def fetch_latest_release(repo: str) -> dict:
|
|
51
|
+
"""Latest published (non-draft, non-prerelease) GitHub release."""
|
|
52
|
+
if not _REPO_RE.match(repo):
|
|
53
|
+
raise ValueError(f"Not a GitHub owner/repo: {repo!r}")
|
|
54
|
+
req = urllib.request.Request(
|
|
55
|
+
f"https://api.github.com/repos/{repo}/releases/latest",
|
|
56
|
+
headers={"Accept": "application/vnd.github+json", "User-Agent": "Codetta-update-check"},
|
|
57
|
+
)
|
|
58
|
+
with urllib.request.urlopen(req, timeout=5) as res: # nosec B310: fixed https://api.github.com URL
|
|
59
|
+
return json.loads(res.read().decode("utf-8"))
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _github_url(url: object) -> str | None:
|
|
63
|
+
"""Only real GitHub links are passed to the page (never javascript: etc.)."""
|
|
64
|
+
return url if isinstance(url, str) and url.startswith("https://github.com/") else None
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class UpdateChecker:
|
|
68
|
+
def __init__(
|
|
69
|
+
self,
|
|
70
|
+
current: str,
|
|
71
|
+
repo: str = DEFAULT_REPO,
|
|
72
|
+
enabled: bool | Callable[[], bool] = True, # a callable is asked each time
|
|
73
|
+
fetch: Fetcher = fetch_latest_release,
|
|
74
|
+
ttl: float = CHECK_EVERY,
|
|
75
|
+
) -> None:
|
|
76
|
+
self.current = current
|
|
77
|
+
self.repo = repo
|
|
78
|
+
self._enabled = enabled
|
|
79
|
+
self.fetch = fetch
|
|
80
|
+
self.ttl = ttl
|
|
81
|
+
self._lock = threading.Lock()
|
|
82
|
+
self._result: dict | None = None
|
|
83
|
+
self._checked_at = 0.0
|
|
84
|
+
|
|
85
|
+
@property
|
|
86
|
+
def enabled(self) -> bool:
|
|
87
|
+
return bool(self._enabled()) if callable(self._enabled) else bool(self._enabled)
|
|
88
|
+
|
|
89
|
+
MIN_FORCE_INTERVAL = 60 # seconds; "Check for updates" can't hammer GitHub
|
|
90
|
+
|
|
91
|
+
def status(self, force: bool = False) -> dict:
|
|
92
|
+
"""Current version, and the latest release if the check is on."""
|
|
93
|
+
base = {
|
|
94
|
+
"current": self.current,
|
|
95
|
+
"enabled": self.enabled,
|
|
96
|
+
"latest": None,
|
|
97
|
+
"update_available": False,
|
|
98
|
+
"release_url": None,
|
|
99
|
+
"notes": None,
|
|
100
|
+
"published_at": None,
|
|
101
|
+
"checked_at": None,
|
|
102
|
+
"error": None,
|
|
103
|
+
"note": None, # neutral info, e.g. no releases published yet
|
|
104
|
+
}
|
|
105
|
+
if not self.enabled:
|
|
106
|
+
return base
|
|
107
|
+
with self._lock:
|
|
108
|
+
age = time.time() - self._checked_at
|
|
109
|
+
fresh = self._result is not None and age < self.ttl
|
|
110
|
+
if (force and age >= self.MIN_FORCE_INTERVAL) or not fresh:
|
|
111
|
+
self._result = self._check()
|
|
112
|
+
self._checked_at = time.time()
|
|
113
|
+
return {**base, **self._result, "checked_at": int(self._checked_at)}
|
|
114
|
+
|
|
115
|
+
def _check(self) -> dict:
|
|
116
|
+
try:
|
|
117
|
+
release = self.fetch(self.repo)
|
|
118
|
+
except urllib.error.HTTPError as exc:
|
|
119
|
+
if exc.code == 404:
|
|
120
|
+
return {"note": "No releases published yet"}
|
|
121
|
+
return {"error": f"GitHub answered {exc.code}"}
|
|
122
|
+
except (urllib.error.URLError, TimeoutError, OSError, ValueError) as exc:
|
|
123
|
+
return {"error": f"Couldn't reach GitHub ({exc.__class__.__name__})"}
|
|
124
|
+
tag = release.get("tag_name")
|
|
125
|
+
latest = ".".join(map(str, parse_version(tag))) if parse_version(tag) else None
|
|
126
|
+
return {
|
|
127
|
+
"latest": latest,
|
|
128
|
+
"update_available": is_newer(tag, self.current),
|
|
129
|
+
"release_url": _github_url(release.get("html_url")),
|
|
130
|
+
"notes": (release.get("body") or "")[:4000] or None,
|
|
131
|
+
"published_at": release.get("published_at"),
|
|
132
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""Codetta's plugin API. See docs/plugins.md for the full guide.
|
|
2
|
+
|
|
3
|
+
A plugin is a folder in ``<config>/plugins/<id>/`` with a ``plugin.json`` and a Python
|
|
4
|
+
file. Codetta imports it only after you enable it (Account -> Plugins) and calls its
|
|
5
|
+
``setup(codetta)`` with a :class:`PluginAPI`::
|
|
6
|
+
|
|
7
|
+
# plugin.py
|
|
8
|
+
def setup(codetta):
|
|
9
|
+
codetta.add_action(
|
|
10
|
+
id="shout", label="UPPERCASE titles",
|
|
11
|
+
description="Make every title upper case.",
|
|
12
|
+
fields=["title"],
|
|
13
|
+
run=lambda tags: {"title": [t.upper() for t in tags.get("title", [])]},
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
An *action* is a batch change to tags: Codetta calls ``run(tags)`` for each chosen track
|
|
17
|
+
(``tags`` maps lower-case tag names to lists of strings) and ``run`` returns the tags it
|
|
18
|
+
wants changed (a value of ``None`` or ``[]`` removes that tag; anything not returned is
|
|
19
|
+
left alone). Codetta shows a preview, writes with its usual safe writes, and logs one
|
|
20
|
+
undoable activity entry. ``run`` must not touch files itself.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
from collections.abc import Callable
|
|
26
|
+
from dataclasses import dataclass, field
|
|
27
|
+
|
|
28
|
+
API_VERSION = 1 # bumped only when a change would break existing plugins
|
|
29
|
+
|
|
30
|
+
TagChanges = dict[str, "list[str] | str | None"]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass(frozen=True)
|
|
34
|
+
class Action:
|
|
35
|
+
id: str # "<plugin id>.<action id>"
|
|
36
|
+
label: str
|
|
37
|
+
description: str
|
|
38
|
+
run: Callable[[dict[str, list[str]]], TagChanges | None]
|
|
39
|
+
plugin: str
|
|
40
|
+
fields: tuple[str, ...] = field(default_factory=tuple) # the tags it reads/changes (shown to people)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class PluginError(Exception):
|
|
44
|
+
"""A plugin did something it shouldn't (a bad id, a duplicate...)."""
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class PluginAPI:
|
|
48
|
+
"""What a plugin's ``setup`` receives. Only add things here in backwards-compatible ways."""
|
|
49
|
+
|
|
50
|
+
api_version = API_VERSION
|
|
51
|
+
|
|
52
|
+
def __init__(self, plugin_id: str, register: Callable[[Action], None]) -> None:
|
|
53
|
+
self.plugin_id = plugin_id
|
|
54
|
+
self._register = register
|
|
55
|
+
|
|
56
|
+
def add_action(self, *, id: str, label: str, run: Callable, description: str = "", # noqa: A002
|
|
57
|
+
fields: list[str] | tuple[str, ...] = ()) -> None:
|
|
58
|
+
if not id or not id.replace("-", "").replace("_", "").isalnum() or len(id) > 40:
|
|
59
|
+
raise PluginError(f"Action id {id!r}: use letters, numbers, - and _ (up to 40)")
|
|
60
|
+
if not callable(run):
|
|
61
|
+
raise PluginError(f"Action {id!r}: run must be a function")
|
|
62
|
+
self._register(Action(f"{self.plugin_id}.{id}", str(label)[:60], str(description)[:300], run, self.plugin_id,
|
|
63
|
+
tuple(str(f).lower() for f in fields)))
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"""Tidy-up actions that ship with Codetta, written exactly like a plugin anyone could write."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
|
|
7
|
+
# Things download sites add to titles.
|
|
8
|
+
_NOISE = re.compile(
|
|
9
|
+
r"\s*[\(\[]\s*(official\s+(music\s+)?(video|audio|lyric video|visualizer)|lyrics?|audio|hq|hd|"
|
|
10
|
+
r"explicit|clean|free\s*(dl|download)|visualizer)\s*[\)\]]", re.IGNORECASE)
|
|
11
|
+
_FEAT = re.compile(r"\b(?:ft|feat|featuring)\b\.?(?=\s)", re.IGNORECASE) # "ft", "ft.", "Feat", "featuring" -> "feat."
|
|
12
|
+
_SMALL = {"a", "an", "and", "as", "at", "but", "by", "for", "in", "nor", "of", "on", "or", "the", "to", "vs", "via"}
|
|
13
|
+
_ALWAYS_LOWER = {"feat", "ft", "vs", "x"} # "Song ft. Zayn", "A vs. B": lower case wherever they are
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _title_case(text: str) -> str:
|
|
17
|
+
words = text.split(" ")
|
|
18
|
+
out = []
|
|
19
|
+
for i, w in enumerate(words):
|
|
20
|
+
if not w:
|
|
21
|
+
out.append(w)
|
|
22
|
+
continue
|
|
23
|
+
core = w.strip("([{\"'")
|
|
24
|
+
if w.isupper() and len(core) > 1 and not core.isalpha(): # "BPM", "R&B", "4x4": leave them
|
|
25
|
+
out.append(w)
|
|
26
|
+
elif core.lower().rstrip(".") in _ALWAYS_LOWER and i > 0:
|
|
27
|
+
out.append(w.lower())
|
|
28
|
+
elif 0 < i < len(words) - 1 and core.lower() in _SMALL:
|
|
29
|
+
out.append(w.lower())
|
|
30
|
+
else:
|
|
31
|
+
lead = len(w) - len(w.lstrip("([{\"'"))
|
|
32
|
+
out.append(w[:lead] + w[lead:lead + 1].upper() + w[lead + 1:].lower() if not any(c.isupper() for c in w[lead + 1:])
|
|
33
|
+
or w.isupper() else w)
|
|
34
|
+
return " ".join(out)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _each(tags: dict, key: str, fn) -> dict | None:
|
|
38
|
+
old = tags.get(key) or []
|
|
39
|
+
new = [fn(v) for v in old]
|
|
40
|
+
return {key: new} if new != old else None
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def setup(codetta) -> None:
|
|
44
|
+
codetta.add_action(
|
|
45
|
+
id="clean-titles", label="Clean up titles",
|
|
46
|
+
description="Remove “(Official Video)”, “[Explicit]”, “(Lyrics)”, “(Free DL)” and similar from titles.",
|
|
47
|
+
fields=["title"],
|
|
48
|
+
run=lambda tags: _each(tags, "title", lambda t: " ".join(_NOISE.sub("", t).split())),
|
|
49
|
+
)
|
|
50
|
+
codetta.add_action(
|
|
51
|
+
id="feat", label="Write features as “feat.”",
|
|
52
|
+
description="Turn “ft.”, “ft”, “featuring” into “feat.” in titles and artists.",
|
|
53
|
+
fields=["title", "artist"],
|
|
54
|
+
run=lambda tags: {**(_each(tags, "title", lambda t: _FEAT.sub("feat.", t)) or {}),
|
|
55
|
+
**(_each(tags, "artist", lambda t: _FEAT.sub("feat.", t)) or {})} or None,
|
|
56
|
+
)
|
|
57
|
+
codetta.add_action(
|
|
58
|
+
id="title-case", label="Title Case",
|
|
59
|
+
description="Capitalise titles: “night drive in the city” → “Night Drive in the City”. Words in capitals stay.",
|
|
60
|
+
fields=["title"],
|
|
61
|
+
run=lambda tags: _each(tags, "title", _title_case),
|
|
62
|
+
)
|
|
63
|
+
codetta.add_action(
|
|
64
|
+
id="trim", label="Trim spaces",
|
|
65
|
+
description="Remove extra spaces at the start, end and inside every text tag.",
|
|
66
|
+
fields=["title", "artist", "album", "albumartist", "genre"],
|
|
67
|
+
run=lambda tags: {k: [" ".join(v.split()) for v in tags.get(k, [])] for k in
|
|
68
|
+
("title", "artist", "album", "albumartist", "genre")
|
|
69
|
+
if [" ".join(v.split()) for v in tags.get(k, [])] != (tags.get(k) or [])} or None,
|
|
70
|
+
)
|
codetta/web/__init__.py
ADDED
|
File without changes
|