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
codetta/CHANGELOG.md ADDED
@@ -0,0 +1,153 @@
1
+ # Changelog
2
+
3
+ All notable changes to Codetta. Versions follow [Semantic Versioning](https://semver.org/).
4
+
5
+ ## 0.8.1 (2026-11-19)
6
+
7
+ - **Run it on your own computer:** no server or Docker needed. `pipx install codetta`, then `codetta` opens your Music folder in the browser (Linux and macOS; Windows support is coming). `codetta set-password` and `codetta sign-out-all` work there too. See [On your own computer](docs/install.md#on-your-own-computer).
8
+ - **Fixed:** an album now lists its tracks by track number, not file name, so after a MusicBrainz match renumbers them they're in the right order straight away.
9
+
10
+ ## 0.8.0 (2026-11-18)
11
+
12
+ - **Big libraries, much faster** (measured on 105,000 tracks):
13
+ - Reading your library the first time is about **4× faster** (139 → 34 seconds): helper processes share the work, then stop. `CODETTA_INDEX_WORKERS` sets how many.
14
+ - A folder of **5,000 tracks opens in a quarter of a second** on the server (was 6.5 s) and draws on screen without freezing: the first screenful at once, the rest a batch at a time.
15
+ - The Library page with 2,000 folders draws in a quarter of a second, without a freeze.
16
+ - **Search** of everything: 1.5 s → 0.26 s; tag searches like `genre: jazz` 0.27 → 0.07 s.
17
+ - **Library health** checks 10,000 albums in under 4 seconds (was 7), then shows its last answer instantly and re-checks in the background after changes. Long lists load 200 at a time with **Show more**.
18
+ - **Changing a tag on 1,000 files** at once: 10.7 → 5.6 seconds, still one safe write per file and one undo.
19
+ - **Memory** on a 100,000-track library: about 130 MB (was up to 500 MB).
20
+ - **Find & replace** in tags, for a folder, a selection or search results: remove "(Official Audio)" from every title, turn "ft." into "feat." Pick one tag or all text tags, match case, or use a pattern (regex). You see every change first, and Activity can undo it.
21
+ - **Actions:** one-tap tidy-ups with a preview: **Clean up titles** (removes "(Official Video)", "[Explicit]", "(Lyrics)", "(Free DL)"…), **Write features as "feat."**, **Title Case** and **Trim spaces**.
22
+ - **Plugins:** add your own actions, or ones other people wrote. Put a plugin's folder in `config/plugins/` and turn it on in **Account → Plugins** (they're off until you do). The built-in actions are written the same way. See the [plugin guide](docs/plugins.md).
23
+ - **Rename folder:** every file moves with it, nothing is overwritten, and it's one undo.
24
+ - On phones, Organize, Find & replace, Actions and Rename folder are in a **…** menu next to the album's other buttons.
25
+ - **Privacy, written down:** [PRIVACY.md](PRIVACY.md) says what Codetta keeps and what it sends (nothing, until you turn a connection on). No tracking, analytics or telemetry of any kind, and tests now check that it stays that way.
26
+ - **Glass, grounded:** menus and the search suggestions have more body, so what's behind them is a soft hint instead of readable text.
27
+ - Your search index is rebuilt once after updating (it now keeps a sort order, so results come back in library order without extra work).
28
+
29
+ ## 0.7.1 (2026-11-18)
30
+
31
+ - **Frosted glass:** sheets, menus, notifications, toasts, the selection bar and the now-playing pill float on frosted glass, with the page blurred softly behind sheets (solid panels where blur isn't available or "reduce transparency" is on).
32
+ - **Fresher motion:** one quick, springy curve everywhere. Sheets settle in, toasts and menus pop, buttons give a little when pressed, folders lift on hover, the first rows ripple in when you change pages, and covers settle into place. The Control Center opens with the same quick motion as the other sheets. "Reduce motion" is respected.
33
+ - Rounder buttons and badges, to match.
34
+ - **Tag Loadouts are now Tag Presets**, everywhere. Your saved ones move over by themselves (from `config/loadouts/` to `config/presets/`).
35
+ - **Compact actions:** Apply preset, Organize and (on phones) Select are icon buttons now, and show their name when you point at them. On phones the album's actions fit on one row.
36
+ - **A real player:** pressing play queues the rest of the album (or search results) after the track, and it carries on to the next one by itself. **Shuffle**, **previous** and **next** (also from your lock screen and headphones). Tap the now-playing pill for the full player: a big cover, **Up next** (jump to any track, or take one out) and **Lyrics**: synced lyrics follow along line by line (tap a line to jump there), plain lyrics show as they are. Lyrics come from the track's tag or a `.lrc` file next to it.
37
+
38
+ ## 0.7.0 (2026-11-18)
39
+
40
+ - **Library health** (Level Up #4): a card on the Library page ("23 things to look at") opens one list of what's worth fixing across your whole library: albums that show up split in your player (album name, album artist or year spelled differently, features without an album artist), missing tracks, the same track number twice, missing disc numbers, no cover or a small one, missing basic tags, the same album in two folders, the same song twice, unreadable files, and MP3s inside a FLAC album. It reads Codetta's search index, so checking thousands of albums takes under a second and no music file is opened. Obvious fixes are one tap ("Use “Kehlani” as the album artist", "Number from file names", "Number from disc folders"), with a preview first and one undo in Activity; everything else opens the album, Find in MusicBrainz or (if connected) Find in slskd. Ignore anything you're happy with, and switch any check off under **Checks**. Library health is optional as a whole: a short setup step asks whether you want it (handy to leave off if your library is named exactly the way you want it), and **Account → Library health** switches it on or off any time. Off means no card and nothing is checked.
41
+ - **Search anything:** the search bar now says "Search anything" and, when you tap it, offers the places you can search besides your library. **`!mb`** (new) searches MusicBrainz for artists and releases: an artist page (who they are, years active, links, every album, EP and single) and a release page (cover, label, catalog number, tracklist), each marked **In your library** when you have it, with **Open in library**, and **Find in slskd** if that's connected. Each bang is offered only while its connection is on. Back and forward work across these pages.
42
+ - The search bar opens wider while you use it and settles back with a softer motion, and its suggestions fade in and out.
43
+ - **Account, redesigned** (try it): it now grows straight out of your profile picture like Control Center, on frosted glass, with tiles that light up for Theme, Library health and Advanced mode, corners that follow the panel's curve, and Connections and Password opening in place.
44
+ - **You can always tell it's working:** a thin line under the top bar while Codetta waits on the server, a clear "Looking up … on MusicBrainz" page with placeholders while MusicBrainz answers, and a busy state when a Soulseek search is sent. If MusicBrainz says it's busy, Codetta waits a moment and tries once more.
45
+ - **Input checks everywhere:** every field the server accepts has sensible limits, IDs are checked before anything else happens, slskd's address and API key are checked as you save them (with a clear message in the form), and searches need at least two letters or numbers.
46
+ - Updates reach your browser right away: Codetta's script and styles are now always checked with the server before a cached copy is used.
47
+ - **README:** Codetta is presented as what it mainly is, a manager for your music library (fix tags, match on MusicBrainz, organize, bring in new music); Soulseek through slskd is one optional integration among the connections.
48
+
49
+ ## 0.6.2 (2026-11-18)
50
+
51
+ - **Security:** a downloaded file's tags can no longer steer where Organize or the inbox puts it. A name starting with "@" (like an album artist "@replaced") used to point at one of Codetta's own folders; it now becomes "@", which looks the same. The inbox can no longer be set to the folder that keeps replaced albums, and a Soulseek download is only ever matched to files that arrived for it (an older album in the inbox with the same file names is never taken for it, so blocklisting can't delete it). One look at the inbox also stops after 5,000 folders.
52
+ - **Faster on phones:** the page, its script and styles and every API answer are now sent gzip-compressed (about a quarter of the size; the app's code goes from about 310 KB to 80 KB). Audio, images and fonts are sent as they are.
53
+ - **Faster folders:** Codetta remembers the tags of files that haven't changed, so opening a folder again doesn't read every file again. Any change, by Codetta or another program, is picked up straight away.
54
+ - **Less disk:** Soulseek download progress is saved every 30 seconds instead of every few seconds, finished requests keep a summary instead of every file list, and the most recent 50 requests are kept.
55
+ - **Replaced albums are kept for 30 days** (like "Recently Deleted"), then removed. Undo works until then.
56
+
57
+ ## 0.6.1 (2026-11-18)
58
+
59
+ - **Fixed:** on phones, the notifications panel and pop-ups ran off the left edge of the screen (the bell moved in from the edge with 0.6.0's new top bar). They now always stay on screen, and are a little more compact on phones.
60
+
61
+ ## 0.6.0 (2026-11-18)
62
+
63
+ - **Soulseek through slskd** (Level Up #3): a new connection for people who run [slskd](https://github.com/slskd/slskd). Type `!slskd` in the search bar and it becomes a **slskd** chip: what you type next is searched on Soulseek (`*` works as a wildcard for filtered names, like `*-Pain`). Or press **Find in slskd** on an album to fill the search bar with its artist and album, ready to edit. Codetta picks the best copy (lossless first by default, then free upload slots, queue and speed), downloads it into your inbox, moves on to the next copy if one fails or stalls, and asks before it joins your library: **Import**, **Blocklist & try next**, or **Choose another**. A download from an album's button replaces that album (the old copy is kept so Activity can undo it). Turn off *Review each download* to let exact MusicBrainz matches file themselves. Set it up in the new setup step or **Account → Connections**; Codetta warns you if slskd isn't sharing a folder, since Soulseek users often refuse people who share nothing. `CODETTA_SLSKD`, `CODETTA_SLSKD_URL`, `CODETTA_SLSKD_API_KEY`.
64
+ - **A roomier top bar on phones:** the tools sit beside the logo and the search bar gets its own full-width row, with a **Cancel** button that slides in while you use it (like iOS). On computers the search bar widens while you use it.
65
+ - The Inbox's **Soulseek** and **Settings** are proper buttons now.
66
+ - **Download progress:** an album that's still arriving in the inbox shows a progress bar with how many files are in and roughly how long the rest will take (from slskd, for anything downloading there, started from Codetta or not). Soulseek downloads in the Soulseek sheet show the time left too.
67
+ - **README:** rewritten for what Codetta is now: find, import, match, fix and file your music, with an updated comparison table and FAQ.
68
+
69
+ ## 0.5.0 (2026-11-18)
70
+
71
+ - **Import inbox** (Level Up #2): pick the folder new music lands in (downloads, rips). Codetta groups it into albums (disc folders join their album; loose tracks are one item each), finds each on MusicBrainz (by tags, then by sound if AcoustID is on), and files it into your library: MusicBrainz tags + your Organize pattern, each an undoable activity entry. Confident matches show "Ready to file" (or file themselves if you allow it); the rest wait for a review in the familiar match dialog. Albums already in your library are never overwritten. Inbox button in the top bar with a count; optional check every 15 minutes (off by default so idle disks can sleep). The inbox can be a folder outside your music folder: mount your downloads (e.g. slskd's) at `/inbox` (or set `CODETTA_INBOX_DIR`); files are copied across, checked, then removed from the downloads folder. Albums that are still arriving wait until their files have been still for 2 minutes.
72
+ - **Easier setup:** after creating your account, a few short steps: online features, how your folders should be named, and where new music arrives. Each is skippable and changeable later. Existing installs see only the new steps, once.
73
+ - **What's new:** this changelog in the app. It pops up once after setup and after each update, and there's a "What's new" link in the footer, in Account, and on the sign-in screen.
74
+ - **Now playing:** a pill grows out of a circle at the bottom of the screen while a track plays: cover (turning like a record), title, artist, time, play/pause, stop, and a thin line you can drag to seek. Music keeps playing while you browse; tap the title to jump back to its album.
75
+ - **Notifications:** a bell next to your account picture. Things Codetta does in the background (the inbox finished looking things up, an album filed itself, a new version is out) pop out of the bell for a few seconds, and the bell keeps the list. Tap one to go straight there.
76
+ - **Fixed:** an album's genre chip only showed the first genre when genres were separated with ";". It now lists every genre, separated by commas, however the file separates them (";", ",", "|" or separate values).
77
+
78
+ - **Organize** (Level Up #1): rename and move files into folders from their tags with a pattern like `{albumartist|artist}/{album}[ ({year})]/{disctrack} {title}`. Presets, one-tap tag buttons and a live example; a preview of every move before anything happens. Names are made safe for any filesystem or network share, nothing is ever overwritten (conflicts are listed instead), lyrics files and the album's cover, booklet and scans move along, and emptied folders are tidied away. One undoable entry in the activity log. Files without artist/album tags are flagged before they'd land in "Unknown Artist".
79
+
80
+ - **Play a track** from the list: a play button at the end of every row (it grows to "Play" when you point at it). Plays the file straight from your server, with seeking and lock-screen/headphone controls. Nothing is converted or cached; formats your browser can't play (WMA, DSF, WavPack…) get no button.
81
+ - **Multi-disc albums** read like a streaming service: a "Disc 2" line (with the disc subtitle) between discs, tracks grouped by disc, and pointing at a row shows "2/01". The disc icon spins when you point at it, and slowly while that disc is playing.
82
+
83
+ ## 0.4.1 (2026-11-18)
84
+
85
+ - The dashboard icons (`/static/icons/`) are now included in the Docker image (0.4.0 left them out).
86
+
87
+ ## 0.4.0 (2026-11-18)
88
+
89
+ - **Offline unless you opt in.** Online features are now *connections*, all off until you choose. After creating your account (or on first start after upgrading) a welcome card asks: stay offline, or turn on online features, with a switch for each one saying exactly what it sends and where. Change them any time in **Account → Connections**. `CODETTA_MUSICBRAINZ`, `CODETTA_LYRICS_LOOKUP` and `CODETTA_UPDATE_CHECK` (`on`/`off`) lock a switch from your compose file; `CODETTA_OFFLINE=on` blocks them all.
90
+ - **Changed:** Find lyrics and the update check used to be on by default. They're now off until you turn them on (the welcome card offers this once).
91
+ - **Match on MusicBrainz:** find the release for an album folder (or selected tracks) by its tags or a pasted musicbrainz.org link, compare editions (year, country, format, label, catalog number, track count, match score), then review a per-file preview before writing. Files are paired with tracks by disc/track number, then title and length, and any pairing can be changed. Choose the fields (titles, credits from recording and work relationships, release details, sort names, MusicBrainz IDs and ISRCs, genres), replace or only fill empty tags, and add cover art from the Cover Art Archive. One activity entry, undoable as a whole (tags and cover together). Respects MusicBrainz's one-request-a-second limit; `CODETTA_MUSICBRAINZ_URL` points it at your own mirror.
92
+ - **Identify by sound (AcoustID):** a new connection that recognises tracks by their audio, even untagged ones. In the match dialog, **Listen** fingerprints each file on your server with Chromaprint's `fpcalc` and sends only those codes and track lengths to AcoustID. Releases holding most of your tracks are offered first ("9 of your 10 tracks are on it"), and files pair with their exact recordings. The Docker image now includes Chromaprint's official static `fpcalc` (about 9 MB, checksum-verified). `CODETTA_ACOUSTID`, `CODETTA_ACOUSTID_KEY`, `CODETTA_FPCALC`.
93
+ - MusicBrainz IDs (release, release group, recording, release track, artist, album artist, work) and `script` are stored the way Picard writes them in every format, including M4A and WMA.
94
+ - **Find in MusicBrainz** button on album pages, beside the genre (phones: "Find", first in the action row), with a MusicBrainz-coloured edge that shifts and glows on hover.
95
+ - **Dashboard icons:** the Codetta icon in full colour, light (for dark dashboards) and dark (for light dashboards), as SVG, PNG and WebP, served at `/static/icons/` so Homepage, Homarr or Dashy can point straight at them.
96
+ - Account → Connections opens and closes (the closed row says what's on), and the sound lookup button reads **Listen** → **Listening…** while it works.
97
+ - With sign-in turned off, the account button now opens Settings, so connections and Advanced mode stay reachable.
98
+
99
+ ## 0.3.1 (2026-11-18)
100
+
101
+ - The browser tab and home-screen icon now update to the new logo right away (they were being kept from the browser's cache).
102
+
103
+ ## 0.3.0 (2026-11-18)
104
+
105
+ - A new look, "liner notes": Codetta now reads like the credits pages of a CD or LP booklet. New lowercase wordmark and icon, the Schibsted Grotesk typeface (bundled), booklet-white and booklet-black themes, and ink rules and hairlines instead of boxes.
106
+ - Each album lends Codetta a colour picked from its cover (adjusted for readable contrast), used for the active track, changed fields, section heads and the logo's square, crossfading as you move between albums.
107
+ - Album folders open as a booklet spread: large cover, album title, artist, year, track count and total runtime, and a genre chip. Columns that would repeat the same value on every row (album, artist, format, cover) are left out; phones show track numbers.
108
+ - The editor reads like a credits sheet: labels beside values on hairlines, with the field box appearing when you point at or edit it.
109
+ - Sign-in is a clean title page; the folder grid is a contents page; phones show one back link instead of a cramped breadcrumb.
110
+ - Accessibility: text on coloured fills switches to dark in dark mode for readable contrast; checkmarks are drawn icons.
111
+
112
+ ## 0.2.0 (2026-11-17)
113
+
114
+ - 10 more formats: WAV, AIFF, DSF (DSD), TrueAudio, MP2, WavPack, WMA, M4B audiobooks, Ogg FLAC and Speex, with album art and every editor field on each. Codetta now handles 15 file types.
115
+ - Sort names (title, artist, album, album artist, composer) and classical fields (work, movement, movement number and count, show movement) plus subtitle, stored where Picard puts them in every format.
116
+ - Advanced mode (account menu): a Raw tags section in the editor lists every stored field exactly as the file has it (ID3 frames, MP4 atoms, Vorbis comments, APEv2 items, WMA attributes, pictures). Read-only.
117
+ - Lyrics: plain or synced (LRC) in a roomy editor box with a "Synced lyrics · 42 timed lines" hint; stored where players look (Vorbis LYRICS, ID3 USLT, MP4 ©lyr, APE Lyrics, WM/Lyrics). Long values are shortened in the activity log (undo still restores the full text).
118
+ - Find lyrics: looks the track up on LRCLIB (only when you press it, sending artist, title, album and length), shows a preview, and offers synced or plain lyrics as an unsaved change. `CODETTA_LYRICS_LOOKUP=off` hides it. First of Codetta's online providers (MusicBrainz and Last.fm will follow the same pattern).
119
+
120
+ ## 0.1.1 (2026-11-17)
121
+
122
+ - README rewritten as a short landing page; details moved to `docs/` (install, configuration, features, FAQ), plus `SECURITY.md` and `CONTRIBUTING.md`.
123
+ - README: an honest comparison with MusicBrainz Picard, beets and Metadata Remote.
124
+ - A quiet footer on the sign-in screen and under the track list: GitHub link · Made with ♥︎ · version.
125
+
126
+ ## 0.1.0 (2026-11-17)
127
+
128
+ First release.
129
+
130
+ - Edit tags on FLAC, MP3, M4A, OGG Vorbis and Opus files, one track or many at once.
131
+ - Navidrome / OpenSubsonic tag set (credits, mood, label, release type, multiple artists…), stored the way MusicBrainz Picard does.
132
+ - Save to folder, copy & paste tags, smart suggestions from the folder, and hints for dates and multi-value fields.
133
+ - Album art: add, replace or remove embedded covers as part of a save, for one track, a selection or the whole folder; thumbnails on every track row.
134
+ - Tag Loadouts with placeholders and a preview before writing.
135
+ - Filter a folder by tag; folders as a list (default) or grid.
136
+ - Works with any language: every script and emoji round-trips exactly; accent-insensitive search; right-to-left names display correctly; sorting ignores case and accents; file names that aren't valid UTF-8 are skipped with a note instead of breaking the folder; emoji get a gentle tip, never a block; commas in names (e.g. "Tyler, The Creator") are never flagged.
137
+ - Comma-separated genres and moods ("Hip-Hop, Trap, Rap", as Navidrome splits them by default) are saved as typed and filter by each part.
138
+ - Activity log of every change, with old and new values, and undo/redo straight from the log (files edited again since are left alone).
139
+ - Safe writes: temporary copy, verify, atomic swap; symlinks, hard links, permissions and cover art preserved.
140
+ - Sign-in with hashed passwords, 30-day sessions, lockout and password reset from the server.
141
+ - Profile pictures: a round photo of your choice in the top bar and account menu (JPEG, PNG, WebP, GIF, AVIF, and HEIC on iPhone/Safari).
142
+ - Version shown on the sign-in screen and account menu, with a check for new releases.
143
+ - Large folders stay fast: a 2,000-track folder opens in under a second and filters in a quarter of a second; a shared album cover downloads once.
144
+ - Simultaneous saves to the same file (two devices, a double-tap) can no longer lose an edit.
145
+ - Security hardening: strict Content Security Policy and security headers, cross-site request protection, request size limits, album art only ever served as an image, stronger password hashing (upgraded automatically at sign-in), optional `CODETTA_ALLOWED_HOSTS`.
146
+ - Search your whole library by tag: `genre: rap, hip-hop`, `artist: drake`, `year: 2024`, or plain words. Commas mean "or", and matching is word-aware ("rap" doesn't find "Trap") and accent-insensitive. Results can be selected and edited like a folder. Backed by a small index in the config folder that updates in the background and right after every edit.
147
+ - Ready-made Docker image for Intel/AMD and ARM servers: `ghcr.io/gavndev/codetta`. Install with one compose file, update with `docker compose pull`.
148
+ - The container runs as your user, with a health check and read-only filesystem.
149
+ - Small footprint: a ~100 MB image (Alpine), ~70 MB of memory, a search index of about 2 KB per track, and no background disk activity when idle (the library is re-checked when you search, at most every 15 minutes), so hard drives can spin down. No per-request access log filling up Docker's logs.
150
+ - First-run setup only works from home networks, Tailscale or the server itself (`CODETTA_ALLOW_PUBLIC_SETUP` to override), so nobody on the internet can claim a fresh install.
151
+ - Requests are bounded (at most 1,000 files and 100,000 characters per tag value), and a file listed twice in one request is edited once. Big Save to folder jobs are sent in batches automatically.
152
+ - On desktop, the selection bar and notifications no longer cover the editor's activity log when the editor is open.
153
+ - On phones, value suggestions for half-width fields (Genre, Disc) are wide enough to read.
codetta/__init__.py ADDED
@@ -0,0 +1,8 @@
1
+ """Codetta: a private, self-hosted music library manager."""
2
+
3
+ from importlib.metadata import PackageNotFoundError, version
4
+
5
+ try:
6
+ __version__ = version("codetta")
7
+ except PackageNotFoundError: # running from a source checkout without installing
8
+ __version__ = "dev"
codetta/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ """``python -m codetta``: the same as the ``codetta`` command."""
2
+
3
+ from codetta.cli.run import main
4
+
5
+ raise SystemExit(main())
File without changes
@@ -0,0 +1,59 @@
1
+ """Codetta admin commands, run on the server.
2
+
3
+ python -m codetta.cli set-password # create the account or reset its password
4
+ python -m codetta.cli sign-out-all # sign out every browser
5
+
6
+ In Docker:
7
+ docker exec -it codetta codetta-admin set-password
8
+
9
+ Uses CODETTA_CONFIG_DIR (default ./config) like the web app, or --config DIR.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import argparse
15
+ import getpass
16
+ import os
17
+ import sys
18
+ from pathlib import Path
19
+
20
+ from codetta.core.auth import AccountStore, AuthError, SessionStore
21
+
22
+
23
+ def main(argv: list[str] | None = None) -> int:
24
+ parser = argparse.ArgumentParser(prog="python -m codetta.cli", description="Codetta admin commands")
25
+ parser.add_argument("--config", default=os.environ.get("CODETTA_CONFIG_DIR") or os.environ.get("CODA_CONFIG_DIR") or "config",
26
+ help="config folder (default: $CODETTA_CONFIG_DIR or ./config)")
27
+ sub = parser.add_subparsers(dest="command", required=True)
28
+ sp = sub.add_parser("set-password", help="create the account, or reset its password")
29
+ sp.add_argument("--username", help="username (default: keep the current one)")
30
+ sub.add_parser("sign-out-all", help="sign out every signed-in browser")
31
+ args = parser.parse_args(argv)
32
+
33
+ config = Path(args.config).expanduser()
34
+ accounts = AccountStore(config / "auth.json")
35
+ sessions = SessionStore(config / "sessions.json")
36
+
37
+ if args.command == "sign-out-all":
38
+ sessions.revoke_all()
39
+ print("Signed out every browser.")
40
+ return 0
41
+
42
+ current = accounts.get()
43
+ username = args.username or (current.username if current else None) or input("Username: ").strip()
44
+ password = getpass.getpass("New password: ")
45
+ if password != getpass.getpass("Repeat password: "):
46
+ print("Passwords didn't match. Nothing was changed.", file=sys.stderr)
47
+ return 1
48
+ try:
49
+ accounts.set_password(username, password)
50
+ except AuthError as exc:
51
+ print(exc, file=sys.stderr)
52
+ return 1
53
+ sessions.revoke_all()
54
+ print(f"Password set for {username!r}. All browsers were signed out; sign in again with the new password.")
55
+ return 0
56
+
57
+
58
+ if __name__ == "__main__":
59
+ sys.exit(main())
codetta/cli/run.py ADDED
@@ -0,0 +1,129 @@
1
+ """The ``codetta`` command: run Codetta on this computer and open it in the browser.
2
+
3
+ codetta # your Music folder, at http://localhost:8111
4
+ codetta ~/Music/FLAC # another folder
5
+ codetta --host 0.0.0.0 # also reachable from your phone on the same network
6
+ codetta set-password # create the account, or reset its password
7
+ codetta sign-out-all # sign out every browser
8
+
9
+ Installed with pipx, uv, Homebrew, snap, winget... Docker doesn't use this (see Dockerfile).
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import argparse
15
+ import os
16
+ import socket
17
+ import sys
18
+ import threading
19
+ import time
20
+ import webbrowser
21
+ from pathlib import Path
22
+
23
+ DEFAULT_PORT = 8111
24
+
25
+
26
+ def default_config_dir() -> Path:
27
+ """Where Codetta keeps its account, settings and index when it's installed as an app."""
28
+ if os.environ.get("SNAP_USER_COMMON"): # snap: the folder that survives updates
29
+ return Path(os.environ["SNAP_USER_COMMON"]) / "config"
30
+ if sys.platform == "win32":
31
+ return Path(os.environ.get("APPDATA") or Path.home() / "AppData" / "Roaming") / "Codetta"
32
+ if sys.platform == "darwin":
33
+ return Path.home() / "Library" / "Application Support" / "Codetta"
34
+ return Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config") / "codetta"
35
+
36
+
37
+ def default_music_dir() -> Path:
38
+ for name in ("Music", "music"):
39
+ if (Path.home() / name).is_dir():
40
+ return Path.home() / name
41
+ return Path.home() / "Music"
42
+
43
+
44
+ def _free(host: str, port: int) -> bool:
45
+ family = socket.AF_INET6 if ":" in host else socket.AF_INET
46
+ with socket.socket(family, socket.SOCK_STREAM) as s:
47
+ try:
48
+ s.bind((host, port))
49
+ return True
50
+ except OSError:
51
+ return False
52
+
53
+
54
+ def _open_when_ready(url: str, host: str, port: int) -> None:
55
+ probe = "127.0.0.1" if host in ("0.0.0.0", "::", "") else host
56
+ end = time.monotonic() + 60
57
+ while time.monotonic() < end:
58
+ try:
59
+ with socket.create_connection((probe, port), timeout=0.5):
60
+ break
61
+ except OSError:
62
+ time.sleep(0.2)
63
+ else:
64
+ return
65
+ try:
66
+ webbrowser.open(url)
67
+ except Exception: # noqa: BLE001 - no browser (a server, a container): the printed address is enough
68
+ pass
69
+
70
+
71
+ def main(argv: list[str] | None = None) -> int:
72
+ argv = list(sys.argv[1:] if argv is None else argv)
73
+ if argv[:1] == ["--codetta-describe-worker"]: # an index helper, in a packaged app
74
+ from codetta.core.describe import _worker_main
75
+ _worker_main()
76
+ return 0
77
+ if argv[:1] and argv[0] in ("set-password", "sign-out-all"):
78
+ from codetta.cli.__main__ import main as admin
79
+ config = os.environ.get("CODETTA_CONFIG_DIR") or str(default_config_dir())
80
+ return admin(["--config", config, *argv])
81
+
82
+ from codetta import __version__
83
+ parser = argparse.ArgumentParser(
84
+ prog="codetta", description="Codetta: a private, self-hosted music library manager. "
85
+ "Runs on this computer and opens in your browser. Admin: codetta set-password | sign-out-all")
86
+ parser.add_argument("music", nargs="?", help="your music folder (default: $CODETTA_MUSIC_DIR or ~/Music)")
87
+ parser.add_argument("--port", type=int, help=f"port (default: {DEFAULT_PORT}, or the next free one)")
88
+ parser.add_argument("--host", default=os.environ.get("CODETTA_HOST", "127.0.0.1"),
89
+ help="address to listen on (default: 127.0.0.1, this computer only; "
90
+ "0.0.0.0 to reach it from other devices on your network)")
91
+ parser.add_argument("--config", help="config folder (default: $CODETTA_CONFIG_DIR or your user's app-data folder)")
92
+ parser.add_argument("--no-browser", action="store_true", help="don't open the browser")
93
+ parser.add_argument("--version", action="version", version=f"Codetta {__version__}")
94
+ args = parser.parse_args(argv)
95
+
96
+ music = Path(args.music or os.environ.get("CODETTA_MUSIC_DIR") or default_music_dir()).expanduser().resolve()
97
+ config = Path(args.config or os.environ.get("CODETTA_CONFIG_DIR") or default_config_dir()).expanduser()
98
+ if not music.is_dir():
99
+ print(f"codetta: there's no folder at {music}. Say which one: codetta /path/to/music", file=sys.stderr)
100
+ return 2
101
+ if not 0 < (args.port or DEFAULT_PORT) < 65536:
102
+ print("codetta: the port must be between 1 and 65535", file=sys.stderr)
103
+ return 2
104
+ port = args.port or next((p for p in range(DEFAULT_PORT, DEFAULT_PORT + 20) if _free(args.host, p)), DEFAULT_PORT)
105
+ if args.port and not _free(args.host, port):
106
+ print(f"codetta: port {port} is in use (is Codetta already running?). Try --port {port + 1}", file=sys.stderr)
107
+ return 2
108
+ config.mkdir(parents=True, exist_ok=True)
109
+ os.environ["CODETTA_MUSIC_DIR"] = str(music)
110
+ os.environ["CODETTA_CONFIG_DIR"] = str(config)
111
+
112
+ import uvicorn
113
+
114
+ from codetta.web.app import app # reads the folders above
115
+
116
+ shown = "localhost" if args.host in ("127.0.0.1", "::1") else args.host
117
+ url = f"http://{shown}:{port}"
118
+ print(f"Codetta {__version__}\n Music: {music}\n Config: {config}\n Open: {url}"
119
+ + ("\n Reachable from other devices on your network too: sign-in protects it." if args.host in ("0.0.0.0", "::") else "")
120
+ + "\nPress Ctrl+C to stop.", flush=True)
121
+ if not args.no_browser:
122
+ threading.Thread(target=_open_when_ready, args=(url, args.host, port), daemon=True).start()
123
+ # No access log and no Server header: Codetta keeps no record of who visits (see PRIVACY.md).
124
+ uvicorn.run(app, host=args.host, port=port, access_log=False, server_header=False, log_level="info")
125
+ return 0
126
+
127
+
128
+ if __name__ == "__main__":
129
+ raise SystemExit(main())
File without changes
@@ -0,0 +1,225 @@
1
+ """AcoustID: identify tracks by how they sound.
2
+
3
+ Two steps, only the second goes online:
4
+
5
+ 1. **Fingerprint** each file on this server with Chromaprint's ``fpcalc``
6
+ (it decodes the first two minutes and boils the sound down to a short
7
+ code). The audio never leaves the server.
8
+ 2. **Look up** the fingerprints on AcoustID, which answers with the
9
+ MusicBrainz *recordings* that sound like that, and the releases they're on.
10
+
11
+ The results feed the MusicBrainz match: releases that contain most of a
12
+ folder's recordings become the candidates, and files pair with tracks by
13
+ recording ID, which beats guessing from track numbers.
14
+
15
+ ``fpcalc`` ships in the Docker image (Chromaprint's official static build).
16
+ Outside Docker: ``apt install libchromaprint-tools`` or ``brew install
17
+ chromaprint``, or point ``CODETTA_FPCALC`` at the binary.
18
+
19
+ AcoustID is free for non-commercial use, at most 3 requests per second.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import json
25
+ import os
26
+ import shutil
27
+ import subprocess # nosec B404: runs only the fpcalc binary, never a shell
28
+ import threading
29
+ import time
30
+ from collections import OrderedDict
31
+ from collections.abc import Callable
32
+ from concurrent.futures import ThreadPoolExecutor
33
+ from dataclasses import dataclass, field
34
+ from pathlib import Path
35
+
36
+ from codetta.core.musicbrainz import MBID_RE
37
+ from codetta.core.providers import ProviderError
38
+
39
+ LOOKUP_URL = "https://api.acoustid.org/v2/lookup"
40
+ # Codetta's application key (registered at acoustid.org for this open-source
41
+ # app, meant to ship with it like Picard's and beets'). CODETTA_ACOUSTID_KEY overrides it.
42
+ DEFAULT_KEY = "CvHAxs0B2q"
43
+ BATCH = 20 # fingerprints per request
44
+ FPCALC_TIMEOUT = 60 # seconds per file; a damaged file mustn't hang the request
45
+ MIN_SCORE = 0.5 # AcoustID's confidence below which a result is ignored
46
+ MAX_FINGERPRINT_CHARS = 20_000
47
+
48
+
49
+ class FingerprintError(Exception):
50
+ """fpcalc is missing, or couldn't read this file."""
51
+
52
+
53
+ def find_fpcalc(configured: str | None = None) -> str | None:
54
+ if configured:
55
+ return configured if os.access(configured, os.X_OK) else None
56
+ return shutil.which("fpcalc")
57
+
58
+
59
+ @dataclass(frozen=True)
60
+ class Fingerprint:
61
+ duration: float
62
+ code: str
63
+
64
+
65
+ Runner = Callable[[list[str]], str] # argv -> stdout; replaceable in tests
66
+
67
+
68
+ def _run(argv: list[str]) -> str:
69
+ try:
70
+ done = subprocess.run(argv, capture_output=True, timeout=FPCALC_TIMEOUT, check=False) # nosec B603: fixed argv
71
+ except subprocess.TimeoutExpired as exc:
72
+ raise FingerprintError("Took too long to read") from exc
73
+ except OSError as exc:
74
+ raise FingerprintError(f"Couldn't run fpcalc: {exc.strerror or exc}") from exc
75
+ if done.returncode != 0:
76
+ msg = done.stderr.decode("utf-8", "replace").strip().removeprefix("ERROR: ")
77
+ raise FingerprintError(msg[:200] or "fpcalc couldn't read this file")
78
+ return done.stdout.decode("utf-8", "replace")
79
+
80
+
81
+ class Fingerprinter:
82
+ """Runs fpcalc, a few files at a time, and remembers results per file version."""
83
+
84
+ def __init__(self, fpcalc: str | None, run: Runner = _run, workers: int = 4) -> None:
85
+ self.fpcalc = fpcalc
86
+ self.run = run
87
+ self.workers = max(1, workers)
88
+ self._cache: OrderedDict[tuple[str, int, int], Fingerprint] = OrderedDict()
89
+ self._lock = threading.Lock()
90
+
91
+ @property
92
+ def available(self) -> bool:
93
+ return self.fpcalc is not None
94
+
95
+ def one(self, path: Path) -> Fingerprint:
96
+ if not self.fpcalc:
97
+ raise FingerprintError("The fingerprint tool (fpcalc) isn't installed on this server")
98
+ st = path.stat()
99
+ key = (str(path), st.st_mtime_ns, st.st_size)
100
+ with self._lock:
101
+ if key in self._cache:
102
+ self._cache.move_to_end(key)
103
+ return self._cache[key]
104
+ # Paths are absolute (resolved inside the library), so they can't be read as options.
105
+ out = self.run([self.fpcalc, "-json", "-length", "120", str(path)])
106
+ try:
107
+ data = json.loads(out)
108
+ fp = Fingerprint(float(data["duration"]), str(data["fingerprint"]))
109
+ except (ValueError, KeyError, TypeError) as exc:
110
+ raise FingerprintError("fpcalc gave an unexpected answer") from exc
111
+ if not fp.code or len(fp.code) > MAX_FINGERPRINT_CHARS or fp.duration <= 0:
112
+ raise FingerprintError("Too short or too quiet to recognise")
113
+ with self._lock:
114
+ self._cache[key] = fp
115
+ while len(self._cache) > 5000:
116
+ self._cache.popitem(last=False)
117
+ return fp
118
+
119
+ def many(self, paths: list[Path]) -> list[Fingerprint | FingerprintError]:
120
+ def safe(p: Path):
121
+ try:
122
+ return self.one(p)
123
+ except FingerprintError as exc:
124
+ return exc
125
+ except OSError as exc:
126
+ return FingerprintError(f"Couldn't read the file: {exc.strerror or exc}")
127
+
128
+ with ThreadPoolExecutor(max_workers=min(self.workers, max(1, len(paths)))) as pool:
129
+ return list(pool.map(safe, paths))
130
+
131
+
132
+ @dataclass
133
+ class Recording:
134
+ id: str
135
+ score: float # AcoustID's confidence, 0..1
136
+ title: str = ""
137
+ artist: str = ""
138
+ duration: float | None = None
139
+ releases: list[str] = field(default_factory=list)
140
+
141
+
142
+ Poster = Callable[[dict[str, str]], object] # form -> parsed JSON
143
+
144
+
145
+ class AcoustID:
146
+ def __init__(self, post: Poster, key: str = DEFAULT_KEY, min_interval: float = 1 / 3,
147
+ clock: Callable[[], float] = time.monotonic, sleep: Callable[[float], None] = time.sleep) -> None:
148
+ self.post = post
149
+ self.key = key
150
+ self.min_interval = min_interval
151
+ self._clock, self._sleep = clock, sleep
152
+ self._lock = threading.Lock()
153
+ self._last = -1e9
154
+
155
+ def lookup(self, fingerprints: list[Fingerprint]) -> list[list[Recording]]:
156
+ """For each fingerprint, the recordings it matches (best first)."""
157
+ out: list[list[Recording]] = []
158
+ for start in range(0, len(fingerprints), BATCH):
159
+ chunk = fingerprints[start:start + BATCH]
160
+ # batch=1 makes AcoustID answer every fingerprint.N (without it only the first).
161
+ form = {"client": self.key, "meta": "recordings releaseids", "format": "json", "batch": "1"}
162
+ for i, fp in enumerate(chunk):
163
+ form[f"duration.{i}"] = str(round(fp.duration))
164
+ form[f"fingerprint.{i}"] = fp.code
165
+ with self._lock:
166
+ wait = self._last + self.min_interval - self._clock()
167
+ if wait > 0:
168
+ self._sleep(wait)
169
+ try:
170
+ data = self.post(form)
171
+ finally:
172
+ self._last = self._clock()
173
+ out.extend(_parse_batch(data, len(chunk)))
174
+ return out
175
+
176
+
177
+ def _parse_batch(data: object, n: int) -> list[list[Recording]]:
178
+ if not isinstance(data, dict) or data.get("status") != "ok":
179
+ msg = (data.get("error") or {}).get("message") if isinstance(data, dict) else None
180
+ raise ProviderError(f"AcoustID answered with an error ({msg or 'unexpected answer'})")
181
+ per_index: dict[int, list] = {}
182
+ if isinstance(data.get("fingerprints"), list):
183
+ for item in data["fingerprints"]:
184
+ if isinstance(item, dict):
185
+ try:
186
+ per_index[int(item.get("index"))] = item.get("results") or []
187
+ except (TypeError, ValueError):
188
+ continue
189
+ elif isinstance(data.get("results"), list): # a single lookup
190
+ per_index[0] = data["results"]
191
+ return [_recordings(per_index.get(i, [])) for i in range(n)]
192
+
193
+
194
+ def _recordings(results: list) -> list[Recording]:
195
+ best: dict[str, Recording] = {}
196
+ for res in results:
197
+ if not isinstance(res, dict):
198
+ continue
199
+ score = res.get("score")
200
+ if not isinstance(score, (int, float)) or score < MIN_SCORE:
201
+ continue
202
+ for rec in res.get("recordings") or []:
203
+ if not isinstance(rec, dict) or not MBID_RE.match(str(rec.get("id", ""))):
204
+ continue
205
+ releases = [r.get("id") for r in rec.get("releases") or [] if isinstance(r, dict)]
206
+ artists = [a.get("name") for a in rec.get("artists") or [] if isinstance(a, dict) and a.get("name")]
207
+ r = Recording(
208
+ id=rec["id"], score=float(score), title=str(rec.get("title") or "")[:500],
209
+ artist=", ".join(artists)[:500],
210
+ duration=rec.get("duration") if isinstance(rec.get("duration"), (int, float)) else None,
211
+ releases=[x for x in releases if isinstance(x, str) and MBID_RE.match(x)],
212
+ )
213
+ if r.id not in best or r.score > best[r.id].score:
214
+ best[r.id] = r
215
+ return sorted(best.values(), key=lambda r: -r.score)
216
+
217
+
218
+ def rank_releases(per_file: dict[str, list[Recording]], limit: int = 10) -> list[tuple[str, int]]:
219
+ """Releases ordered by how many of these files they contain: [(release id, files)]."""
220
+ counts: dict[str, int] = {}
221
+ for recs in per_file.values():
222
+ seen = {rel for r in recs for rel in r.releases}
223
+ for rel in seen:
224
+ counts[rel] = counts.get(rel, 0) + 1
225
+ return sorted(counts.items(), key=lambda kv: -kv[1])[:limit]