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.
Files changed (63) hide show
  1. codetta/CHANGELOG.md +153 -0
  2. codetta/__init__.py +8 -0
  3. codetta/__main__.py +5 -0
  4. codetta/cli/__init__.py +0 -0
  5. codetta/cli/__main__.py +59 -0
  6. codetta/cli/run.py +129 -0
  7. codetta/core/__init__.py +0 -0
  8. codetta/core/acoustid.py +225 -0
  9. codetta/core/activity.py +161 -0
  10. codetta/core/artwork.py +238 -0
  11. codetta/core/auth.py +362 -0
  12. codetta/core/avatar.py +92 -0
  13. codetta/core/changelog.py +51 -0
  14. codetta/core/connections.py +159 -0
  15. codetta/core/describe.py +69 -0
  16. codetta/core/engine.py +470 -0
  17. codetta/core/health.py +520 -0
  18. codetta/core/inbox.py +195 -0
  19. codetta/core/index.py +672 -0
  20. codetta/core/library.py +177 -0
  21. codetta/core/musicbrainz.py +662 -0
  22. codetta/core/notifications.py +77 -0
  23. codetta/core/onboarding.py +39 -0
  24. codetta/core/organize.py +490 -0
  25. codetta/core/plugins.py +183 -0
  26. codetta/core/presets.py +452 -0
  27. codetta/core/providers.py +203 -0
  28. codetta/core/rawtags.py +135 -0
  29. codetta/core/slskd.py +650 -0
  30. codetta/core/tagmap.py +538 -0
  31. codetta/core/undo.py +186 -0
  32. codetta/core/updates.py +132 -0
  33. codetta/plugins/__init__.py +63 -0
  34. codetta/plugins/builtin/__init__.py +3 -0
  35. codetta/plugins/builtin/tidy.py +70 -0
  36. codetta/web/__init__.py +0 -0
  37. codetta/web/app.py +2909 -0
  38. codetta/web/security.py +170 -0
  39. codetta/web/static/app.css +2684 -0
  40. codetta/web/static/app.js +5694 -0
  41. codetta/web/static/apple-touch-icon.png +0 -0
  42. codetta/web/static/fonts/LICENSE-Inter.txt +93 -0
  43. codetta/web/static/fonts/LICENSE-SchibstedGrotesk.txt +93 -0
  44. codetta/web/static/fonts/inter-cyrillic.woff2 +0 -0
  45. codetta/web/static/fonts/schibsted-grotesk.woff2 +0 -0
  46. codetta/web/static/icon.svg +1 -0
  47. codetta/web/static/icons/codetta-dark.png +0 -0
  48. codetta/web/static/icons/codetta-dark.svg +1 -0
  49. codetta/web/static/icons/codetta-dark.webp +0 -0
  50. codetta/web/static/icons/codetta-light.png +0 -0
  51. codetta/web/static/icons/codetta-light.svg +1 -0
  52. codetta/web/static/icons/codetta-light.webp +0 -0
  53. codetta/web/static/icons/codetta.png +0 -0
  54. codetta/web/static/icons/codetta.svg +1 -0
  55. codetta/web/static/icons/codetta.webp +0 -0
  56. codetta/web/static/index.html +473 -0
  57. codetta/web/static/theme.js +12 -0
  58. codetta-0.8.1.dist-info/METADATA +282 -0
  59. codetta-0.8.1.dist-info/RECORD +63 -0
  60. codetta-0.8.1.dist-info/WHEEL +5 -0
  61. codetta-0.8.1.dist-info/entry_points.txt +2 -0
  62. codetta-0.8.1.dist-info/licenses/LICENSE +661 -0
  63. codetta-0.8.1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,203 @@
1
+ """Online metadata providers: the first step toward Codetta plugins.
2
+
3
+ A provider looks something up for one track and returns suggestions; it never
4
+ writes files. The user always sees a preview and decides. LRCLIB (lyrics) lives
5
+ here; MusicBrainz is in ``musicbrainz.py``. Each belongs to a *connection*
6
+ (see ``connections.py``) that is off until the user opts in.
7
+
8
+ Privacy: providers are only called when the user asks (a button press), and
9
+ only send what the lookup needs (artist, title, album, duration).
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ import threading
16
+ import urllib.error
17
+ import urllib.parse
18
+ import urllib.request
19
+ from collections import OrderedDict
20
+ from collections.abc import Callable
21
+ from dataclasses import asdict, dataclass
22
+
23
+ MAX_RESPONSE_BYTES = 2 * 1024 * 1024
24
+ MAX_LYRICS_CHARS = 100_000 # same cap as any tag value
25
+ TIMEOUT = 8
26
+
27
+
28
+ class ProviderError(Exception):
29
+ """The provider couldn't be reached or answered with something unusable."""
30
+
31
+
32
+ @dataclass
33
+ class TrackQuery:
34
+ artist: str
35
+ title: str
36
+ album: str = ""
37
+ duration: float | None = None # seconds
38
+
39
+
40
+ @dataclass
41
+ class LyricsResult:
42
+ provider: str
43
+ artist: str
44
+ title: str
45
+ album: str
46
+ duration: float | None
47
+ synced: str # LRC text, or "" if the provider only has plain lyrics
48
+ plain: str
49
+ instrumental: bool = False
50
+
51
+ def to_dict(self) -> dict:
52
+ return asdict(self)
53
+
54
+
55
+ # (url) -> parsed JSON or None for "not found". Replaceable in tests.
56
+ Fetcher = Callable[[str], object]
57
+
58
+
59
+ class _HttpsOnlyRedirects(urllib.request.HTTPRedirectHandler):
60
+ """Follow redirects (the Cover Art Archive sends you to archive.org), but
61
+ never from https down to plain http."""
62
+
63
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
64
+ if req.full_url.startswith("https://") and not newurl.startswith("https://"):
65
+ raise ProviderError("The service tried to redirect to an insecure address")
66
+ return super().redirect_request(req, fp, code, msg, headers, newurl)
67
+
68
+
69
+ _opener = urllib.request.build_opener(_HttpsOnlyRedirects)
70
+
71
+
72
+ def http_get(url: str, user_agent: str, *, accept: str = "application/json", max_bytes: int = MAX_RESPONSE_BYTES,
73
+ service: str = "the lyrics service", allow_http: bool = False) -> bytes | None:
74
+ """GET a provider URL, size- and time-limited. None means 404 (not found).
75
+
76
+ Only https, unless ``allow_http`` (a self-hosted mirror the admin set up)."""
77
+ if not (url.startswith("https://") or (allow_http and url.startswith("http://"))):
78
+ raise ProviderError("Providers must use https")
79
+ req = urllib.request.Request(url, headers={"User-Agent": user_agent, "Accept": accept})
80
+ try:
81
+ with _opener.open(req, timeout=TIMEOUT) as res: # nosec B310: http(s) only, fixed provider hosts
82
+ data = res.read(max_bytes + 1)
83
+ except urllib.error.HTTPError as exc:
84
+ if exc.code == 404:
85
+ return None
86
+ if exc.code in (429, 503):
87
+ raise ProviderError(f"{service.capitalize()} is busy right now. Try again in a moment.") from exc
88
+ raise ProviderError(f"{service.capitalize()} answered with an error ({exc.code})") from exc
89
+ except (urllib.error.URLError, TimeoutError, OSError) as exc:
90
+ raise ProviderError(f"Couldn't reach {service}. Is the server online?") from exc
91
+ if len(data) > max_bytes:
92
+ raise ProviderError(f"{service.capitalize()} sent an unexpectedly large answer")
93
+ return data
94
+
95
+
96
+ def http_post_json(url: str, user_agent: str, form: dict[str, str], *, service: str,
97
+ max_bytes: int = MAX_RESPONSE_BYTES) -> object:
98
+ """POST a form (gzip-compressed, which fingerprint services accept) and parse the JSON answer."""
99
+ import gzip
100
+
101
+ if not url.startswith("https://"):
102
+ raise ProviderError("Providers must use https")
103
+ body = gzip.compress(urllib.parse.urlencode(form).encode())
104
+ req = urllib.request.Request(url, data=body, method="POST", headers={
105
+ "User-Agent": user_agent, "Accept": "application/json",
106
+ "Content-Type": "application/x-www-form-urlencoded", "Content-Encoding": "gzip",
107
+ })
108
+ try:
109
+ with _opener.open(req, timeout=TIMEOUT * 2) as res: # nosec B310: fixed https provider URL
110
+ data = res.read(max_bytes + 1)
111
+ except urllib.error.HTTPError as exc:
112
+ try: # AcoustID explains errors in its JSON body ("invalid API key")
113
+ detail = json.loads(exc.read(10_000)).get("error", {}).get("message")
114
+ except (ValueError, AttributeError, OSError):
115
+ detail = None
116
+ if exc.code in (429, 503):
117
+ raise ProviderError(f"{service.capitalize()} is busy right now. Try again in a moment.") from exc
118
+ raise ProviderError(f"{service.capitalize()} answered with an error ({detail or exc.code})") from exc
119
+ except (urllib.error.URLError, TimeoutError, OSError) as exc:
120
+ raise ProviderError(f"Couldn't reach {service}. Is the server online?") from exc
121
+ if len(data) > max_bytes:
122
+ raise ProviderError(f"{service.capitalize()} sent an unexpectedly large answer")
123
+ try:
124
+ return json.loads(data)
125
+ except ValueError as exc:
126
+ raise ProviderError(f"{service.capitalize()} sent something that isn't JSON") from exc
127
+
128
+
129
+ def http_get_json(url: str, user_agent: str, *, max_bytes: int = MAX_RESPONSE_BYTES,
130
+ service: str = "the lyrics service", allow_http: bool = False) -> object:
131
+ """GET a JSON document (None for 404)."""
132
+ data = http_get(url, user_agent, max_bytes=max_bytes, service=service, allow_http=allow_http)
133
+ if data is None:
134
+ return None
135
+ try:
136
+ return json.loads(data)
137
+ except ValueError as exc:
138
+ raise ProviderError(f"{service.capitalize()} sent something that isn't JSON") from exc
139
+
140
+
141
+ class LRCLib:
142
+ """https://lrclib.net: free, open, no account, plain and synced lyrics."""
143
+
144
+ name = "LRCLIB"
145
+ base = "https://lrclib.net/api"
146
+
147
+ def __init__(self, fetch: Fetcher):
148
+ self.fetch = fetch
149
+ self._cache: OrderedDict[tuple, LyricsResult | None] = OrderedDict()
150
+ self._lock = threading.Lock()
151
+
152
+ def lyrics(self, q: TrackQuery) -> LyricsResult | None:
153
+ key = (q.artist.casefold(), q.title.casefold(), q.album.casefold(), round(q.duration or 0))
154
+ with self._lock:
155
+ if key in self._cache:
156
+ self._cache.move_to_end(key)
157
+ return self._cache[key]
158
+ result = self._lookup(q)
159
+ with self._lock:
160
+ self._cache[key] = result
161
+ while len(self._cache) > 500:
162
+ self._cache.popitem(last=False)
163
+ return result
164
+
165
+ def _lookup(self, q: TrackQuery) -> LyricsResult | None:
166
+ params = {"artist_name": q.artist, "track_name": q.title}
167
+ if q.album:
168
+ params["album_name"] = q.album
169
+ if q.duration:
170
+ params["duration"] = str(round(q.duration))
171
+ exact = self.fetch(f"{self.base}/get?{urllib.parse.urlencode(params)}")
172
+ if isinstance(exact, dict) and (exact.get("syncedLyrics") or exact.get("plainLyrics") or exact.get("instrumental")):
173
+ return self._result(exact)
174
+ # No exact match (e.g. album or duration differ slightly): search, and
175
+ # take the closest by duration among same-title results.
176
+ found = self.fetch(f"{self.base}/search?{urllib.parse.urlencode({'artist_name': q.artist, 'track_name': q.title})}")
177
+ candidates = [r for r in found if isinstance(r, dict)] if isinstance(found, list) else []
178
+ candidates = [r for r in candidates if r.get("syncedLyrics") or r.get("plainLyrics")]
179
+ if not candidates:
180
+ return None
181
+ if q.duration:
182
+ # Only versions within a few seconds of this file: synced lyrics from a
183
+ # different edit (radio, extended) would be out of time.
184
+ candidates = [r for r in candidates if abs((r.get("duration") or 0) - q.duration) <= 5]
185
+ candidates.sort(key=lambda r: abs((r.get("duration") or 0) - q.duration))
186
+ if not candidates:
187
+ return None
188
+ candidates.sort(key=lambda r: not r.get("syncedLyrics")) # stable: closest synced, else closest
189
+ return self._result(candidates[0])
190
+
191
+ def _result(self, r: dict) -> LyricsResult:
192
+ def text(key: str) -> str:
193
+ value = r.get(key) or ""
194
+ return value[:MAX_LYRICS_CHARS] if isinstance(value, str) else ""
195
+
196
+ duration = r.get("duration")
197
+ return LyricsResult(
198
+ provider=self.name,
199
+ artist=text("artistName"), title=text("trackName"), album=text("albumName"),
200
+ duration=float(duration) if isinstance(duration, (int, float)) else None,
201
+ synced=text("syncedLyrics").strip(), plain=text("plainLyrics").strip(),
202
+ instrumental=bool(r.get("instrumental")),
203
+ )
@@ -0,0 +1,135 @@
1
+ """Raw tag view for Advanced mode: every stored field, exactly as the file has it.
2
+
3
+ The editor shows friendly names ("Album artist"); this lists what's really in
4
+ the file (``TPE2``, ``aART``, ``ALBUMARTIST``, ``Album Artist``, ``WM/AlbumArtist``),
5
+ including fields Codetta doesn't otherwise show and embedded pictures. Read-only.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import base64
11
+ from dataclasses import asdict, dataclass
12
+ from pathlib import Path
13
+
14
+ from mutagen.apev2 import BINARY as APE_BINARY
15
+ from mutagen.apev2 import TEXT as APE_TEXT
16
+ from mutagen.asf import ASFByteArrayAttribute
17
+ from mutagen.flac import Picture
18
+ from mutagen.mp4 import MP4FreeForm
19
+
20
+ from codetta.core.artwork import _asf_unpack, sniff_image_type
21
+ from codetta.core.tagmap import APE_FORMATS, ASF_FORMATS, ID3_FORMATS, MP4_FORMATS
22
+
23
+ MAX_VALUE_CHARS = 2000 # long values (lyrics, fingerprints) are cut for display
24
+
25
+ PICTURE_TYPES = {0: "Other", 3: "Front cover", 4: "Back cover", 6: "Media", 8: "Artist"}
26
+
27
+
28
+ @dataclass
29
+ class RawEntry:
30
+ name: str
31
+ value: str
32
+ kind: str = "text" # "text", "picture" or "binary"
33
+ length: int | None = None # full length when ``value`` was shortened
34
+
35
+
36
+ def _text(name: str, value: str) -> RawEntry:
37
+ if len(value) > MAX_VALUE_CHARS:
38
+ return RawEntry(name, value[:MAX_VALUE_CHARS] + "…", length=len(value))
39
+ return RawEntry(name, value)
40
+
41
+
42
+ def _size(n: int) -> str:
43
+ return f"{n / 1024:.0f} KB" if n >= 1024 else f"{n} bytes"
44
+
45
+
46
+ def _picture(name: str, mime: str, data: bytes, ptype: int | None = None) -> RawEntry:
47
+ mime = mime or sniff_image_type(data) or ""
48
+ parts = [p for p in (PICTURE_TYPES.get(ptype, "") if ptype is not None else "", mime, _size(len(data))) if p]
49
+ return RawEntry(name, " · ".join(parts), kind="picture")
50
+
51
+
52
+ def raw_tags(audio, format_name: str) -> tuple[str, list[dict]]:
53
+ """(tag system, entries) for a file opened with ``engine._open_raw``."""
54
+ tags = audio.tags
55
+ entries: list[RawEntry] = []
56
+
57
+ if format_name in ID3_FORMATS:
58
+ system = f"ID3v2.{tags.version[1]}" if tags is not None else "ID3 (no tags)"
59
+ for key, frame in (tags or {}).items():
60
+ if frame.FrameID == "APIC":
61
+ entries.append(_picture(key, frame.mime, frame.data, frame.type))
62
+ elif hasattr(frame, "text") or hasattr(frame, "people") or hasattr(frame, "url"):
63
+ entries.append(_text(key, str(frame)))
64
+ else:
65
+ data = getattr(frame, "data", b"")
66
+ entries.append(RawEntry(key, _size(len(data)), kind="binary"))
67
+ elif format_name in MP4_FORMATS:
68
+ system = "MP4 atoms"
69
+ for key, values in (tags or {}).items():
70
+ if key == "covr":
71
+ for c in values:
72
+ entries.append(_picture(key, "image/png" if c.imageformat == 14 else "image/jpeg", bytes(c)))
73
+ continue
74
+ shown = []
75
+ for v in values:
76
+ if isinstance(v, MP4FreeForm):
77
+ try:
78
+ shown.append(bytes(v).decode("utf-8"))
79
+ except UnicodeDecodeError:
80
+ shown.append(f"<{_size(len(v))} binary>")
81
+ elif isinstance(v, tuple):
82
+ shown.append("/".join(str(x) for x in v))
83
+ else:
84
+ shown.append(str(v))
85
+ entries.append(_text(key, " / ".join(shown)))
86
+ elif format_name in APE_FORMATS:
87
+ system = "APEv2"
88
+ for key in (tags or {}).keys():
89
+ item = tags[key]
90
+ if item.kind == APE_TEXT:
91
+ entries.append(_text(key, " / ".join(item)))
92
+ elif item.kind == APE_BINARY and key.lower().startswith("cover art"):
93
+ _, _, data = bytes(item.value).partition(b"\x00")
94
+ entries.append(_picture(key, "", data))
95
+ else:
96
+ entries.append(RawEntry(key, _size(len(bytes(item.value))), kind="binary"))
97
+ elif format_name in ASF_FORMATS:
98
+ system = "ASF attributes"
99
+ for key in tags.keys():
100
+ for attr in tags[key]:
101
+ if isinstance(attr, ASFByteArrayAttribute):
102
+ pic = _asf_unpack(bytes(attr.value)) if key == "WM/Picture" else None
103
+ if pic:
104
+ entries.append(_picture(key, pic[2], pic[1], pic[0]))
105
+ else:
106
+ entries.append(RawEntry(key, _size(len(attr.value)), kind="binary"))
107
+ else:
108
+ entries.append(_text(key, str(attr.value)))
109
+ else: # Vorbis comments: FLAC and the Ogg family
110
+ system = "Vorbis comments"
111
+ if tags is not None:
112
+ if getattr(tags, "vendor", ""):
113
+ entries.append(_text("(vendor)", tags.vendor))
114
+ for key, value in tags: # in file order, original spelling
115
+ if key.lower() == "metadata_block_picture":
116
+ try:
117
+ pic = Picture(base64.b64decode(value))
118
+ entries.append(_picture(key, pic.mime, pic.data, pic.type))
119
+ except Exception: # noqa: BLE001 - damaged block
120
+ entries.append(RawEntry(key, f"{len(value)} characters (unreadable picture)", kind="binary"))
121
+ else:
122
+ entries.append(_text(key, value))
123
+ for pic in getattr(audio, "pictures", []): # FLAC picture blocks
124
+ entries.append(_picture("PICTURE", pic.mime, pic.data, pic.type))
125
+
126
+ return system, [asdict(e) for e in entries]
127
+
128
+
129
+ def read_raw(engine, path: Path) -> dict:
130
+ from codetta.core.engine import _open_raw # same opening (and format sniffing) as the editor
131
+
132
+ engine.load_metadata(path) # validates the path and format
133
+ audio, format_name = _open_raw(path)
134
+ system, entries = raw_tags(audio, format_name)
135
+ return {"format": format_name, "system": system, "entries": entries}