subsnip 1.0.0__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.
@@ -0,0 +1,182 @@
1
+ Metadata-Version: 2.4
2
+ Name: subsnip
3
+ Version: 1.0.0
4
+ Summary: Playlist CSV to official 320k MP3s with tags, cover art and synced lyrics
5
+ Author: ddddaaaattttoooo
6
+ License: MIT
7
+ Project-URL: Homepage, https://gitlab.com/ddddaaaattttoooo/subsnip
8
+ Requires-Python: >=3.8
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Requires-Dist: yt-dlp
12
+ Requires-Dist: mutagen
13
+ Dynamic: license-file
14
+
15
+ <p align="center"><img src="https://gitlab.com/ddddaaaattttoooo/subsnip/-/raw/main/assets/logo.png" width="128" alt="subsnip logo"></p>
16
+
17
+ <h1 align="center">subsnip</h1>
18
+
19
+ <p align="center">
20
+ Your playlists on any MP3 player: the official recordings, with proper names, album info, cover art and synced lyrics.
21
+ </p>
22
+
23
+ <p align="center">
24
+ <a href="https://gitlab.com/ddddaaaattttoooo/subsnip/-/pipelines"><img src="https://gitlab.com/ddddaaaattttoooo/subsnip/badges/main/pipeline.svg" alt="tests"></a>
25
+ <a href="https://pypi.org/project/subsnip/"><img src="https://img.shields.io/pypi/v/subsnip" alt="PyPI"></a>
26
+ <img src="https://img.shields.io/badge/license-MIT-blue" alt="MIT license">
27
+ <img src="https://img.shields.io/badge/python-3.8%2B-blue" alt="Python 3.8+">
28
+ <img src="https://img.shields.io/badge/audio-320k%20MP3-blue" alt="320k MP3">
29
+ <img src="https://img.shields.io/badge/platform-Linux%20%7C%20macOS%20%7C%20Windows-blue" alt="Linux, macOS, Windows">
30
+ </p>
31
+
32
+ <p align="center">
33
+ <a href="https://ko-fi.com/ddddaaaattttoooo"><img src="https://img.shields.io/badge/Support-on%20Ko--fi-FF5E5B?style=for-the-badge&logo=kofi&logoColor=white" alt="Support subsnip on Ko-fi"></a>
34
+ <a href="https://discord.gg/gr4uwUyYTG"><img alt="Join the Discord" src="https://img.shields.io/badge/Join-on%20Discord-5865F2?style=for-the-badge&logo=discord&logoColor=white" /></a>
35
+ </p>
36
+
37
+ > Inspired by [spotDL](https://github.com/spotDL/spotify-downloader), but strict: if subsnip can't confirm a song is the official release, it skips it instead of guessing.
38
+
39
+ ---
40
+
41
+ ```
42
+ $ subsnip download ~/Downloads/my_playlist.csv
43
+ 3 already downloaded, 4 to go
44
+ [2/7] Lil Peep - feelz ok
45
+ [3/7] Poshlaya Molly - ШКОЛЬНИК ok
46
+ [5/7] Kino - Пачка сигарет ok
47
+ [4/7] Che - wtf ok
48
+ done
49
+ ```
50
+
51
+ ---
52
+
53
+ ## Installation
54
+
55
+ subsnip needs **Python 3.8+**, **FFmpeg** and **Node.js**.
56
+
57
+ ### Python (recommended)
58
+
59
+ ```sh
60
+ pip install subsnip
61
+ subsnip -h
62
+ ```
63
+
64
+ Update with `pip install -U subsnip`. If pip says "externally-managed-environment" (many Linux distros), use `pipx install subsnip` instead. If `subsnip` isn't found afterwards, use `python3 -m subsnip` (Windows: `python -m subsnip`), or add pip's scripts folder to your `PATH`.
65
+
66
+ **Other options**
67
+
68
+ - From source:
69
+ ```sh
70
+ git clone https://gitlab.com/ddddaaaattttoooo/subsnip
71
+ cd subsnip
72
+ pip install -r requirements.txt
73
+ python3 subsnip.py -h
74
+ ```
75
+
76
+ ### Installing FFmpeg
77
+
78
+ FFmpeg converts and tags the audio.
79
+
80
+ - Windows: `winget install Gyan.FFmpeg`
81
+ - macOS: `brew install ffmpeg`
82
+ - Linux: your package manager, e.g. `sudo apt install ffmpeg`
83
+
84
+ ### Installing Node.js
85
+
86
+ yt-dlp uses Node.js to read YouTube pages.
87
+
88
+ - Windows: `winget install OpenJS.NodeJS`
89
+ - macOS: `brew install node`
90
+ - Linux: your package manager, e.g. `sudo apt install nodejs`
91
+
92
+ ## Usage
93
+
94
+ Export your playlist as CSV with [Exportify](https://exportify.net), then:
95
+
96
+ ```sh
97
+ subsnip [operation] [CSV] [FOLDER]
98
+ ```
99
+
100
+ `FOLDER` defaults to `~/Music/<csv name>`. Run `subsnip -h` for help and `subsnip -V` for the version.
101
+
102
+ **Supported operations**
103
+
104
+ - `download`: downloads every song in the playlist, skipping songs you already have.
105
+ - Usage: `subsnip download my_playlist.csv`
106
+ - Option: `--workers N`, songs downloaded at once (default 3)
107
+ - `check`: compares every song's tags and cover with the playlist. Changes nothing.
108
+ - Usage: `subsnip check my_playlist.csv`
109
+ - `retag`: rewrites tags, cover and lyrics. The audio is untouched.
110
+ - Usage: `subsnip retag my_playlist.csv`
111
+
112
+ ### Output
113
+
114
+ ```
115
+ ~/Music/my_playlist/
116
+ ├── Artist - Song.mp3
117
+ ├── Artist - Song.lrc
118
+ ├── my_playlist.m3u8 playlist in your order
119
+ ├── failed.txt songs with no exact match (only if there are any)
120
+ └── skip.txt your own list of songs to skip (optional)
121
+ ```
122
+
123
+ Copy the folder to your player. Players with synced lyrics read the `.lrc` files; others show the lyrics embedded in the MP3.
124
+
125
+ ### Skipping songs
126
+
127
+ Create `skip.txt` in the music folder:
128
+
129
+ ```
130
+ # never download this one
131
+ Some Artist - Some Song
132
+ # use my own file instead (it takes this song's place in the playlist)
133
+ Other Artist - Other Song = My Artist - My Version
134
+ ```
135
+
136
+ ## Matching and Audio Quality
137
+
138
+ subsnip finds each song in this order and stops at the first exact match:
139
+
140
+ 1. **ISRC**, the code that identifies one exact recording, searched on YouTube Music.
141
+ 2. **Artist and title** on YouTube Music. Artists written in other alphabets (Cyrillic and more) work too.
142
+ 3. **The artist's own SoundCloud upload.**
143
+
144
+ Every match must be an official release by the right artist, within 3 seconds of the playlist's length. Fan uploads, music videos, sped-up edits and live versions are never used. Songs with no exact match go to `failed.txt`.
145
+
146
+ ### Metadata and lyrics
147
+
148
+ Title, all artists, album, album artist, year, ISRC, label, genre, explicit flag and the 640×640 album cover. Lyrics come from [LRCLIB](https://lrclib.net) as a synced `.lrc` file plus lyrics embedded in the MP3. Every song is checked right after download.
149
+
150
+ ### Audio Quality
151
+
152
+ Everything is saved as **320 kbps MP3**, one quality for the whole library, about 140 MB per hour of music.
153
+
154
+ > **Note**
155
+ > subsnip is for personal use. It downloads from YouTube Music and SoundCloud through [yt-dlp](https://github.com/yt-dlp/yt-dlp) and never touches Spotify's audio or any DRM-protected stream. Only download music you have the right to, and follow the terms of the services you use.
156
+
157
+ ## Troubleshooting
158
+
159
+ - **A song is in `failed.txt`.** No official upload with the same length was found. That's on purpose: subsnip won't guess. Add your own copy and list it in `skip.txt`.
160
+ - **"YouTube rate limit hit".** Wait about an hour and run the same command again. Finished songs are skipped.
161
+ - **macOS: SSL certificate errors.** Run "Install Certificates.command" in your Python folder (python.org installs only).
162
+ - **Old yt-dlp.** Update with `pip install -U yt-dlp`, or point the `YTDLP_PATH` environment variable at a [nightly build](https://github.com/yt-dlp/yt-dlp-nightly-builds/releases).
163
+
164
+ **Why a CSV and not a link?** A public playlist page only shows the first 100 songs, and reading playlists directly needs a developer key. Exportify gives the full list with ISRCs, genres and labels in one file.
165
+
166
+ ## Contributing
167
+
168
+ Found a bug or have an idea? Open an [issue](https://gitlab.com/ddddaaaattttoooo/subsnip/-/issues) or a merge request. Run the tests first:
169
+
170
+ ```sh
171
+ python3 test_subsnip.py
172
+ ```
173
+
174
+ ## Credits
175
+
176
+ Made by [ddddaaaattttoooo](https://gitlab.com/ddddaaaattttoooo).
177
+
178
+ Built on [yt-dlp](https://github.com/yt-dlp/yt-dlp), [mutagen](https://github.com/quodlibet/mutagen), [FFmpeg](https://ffmpeg.org), [LRCLIB](https://lrclib.net) and [Exportify](https://exportify.net). Inspired by [spotDL](https://github.com/spotDL/spotify-downloader).
179
+
180
+ ## License
181
+
182
+ This project is licensed under the [MIT](LICENSE) license.
@@ -0,0 +1,8 @@
1
+ subsnip.py,sha256=DFpS33BYG0NEPl6sXCFsI5fTgWKOyhgQxphYlsrlgSY,11085
2
+ subsnip_retag.py,sha256=rBAvCz14kg-q0gsDLFlhVPsAdASNG2C4OFN9VbpGwXY,8551
3
+ subsnip-1.0.0.dist-info/licenses/LICENSE,sha256=5N5JMOVMKLf8dycVQJBcA0hYamaEFwNwu_4wKtqdxuA,1073
4
+ subsnip-1.0.0.dist-info/METADATA,sha256=zd2CA2Zhtgig11lWL_6TS1vjTspx4tgqNsoNYZl8nxo,7234
5
+ subsnip-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
6
+ subsnip-1.0.0.dist-info/entry_points.txt,sha256=VyFh_gwWzoV9aU8B6wyUkW8KN6HoBVVBg_CCbf8VGdQ,41
7
+ subsnip-1.0.0.dist-info/top_level.txt,sha256=0fsImQ-JuNE-pybOT8OCJQRqJriXkd__IZfDjhnODng,22
8
+ subsnip-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ subsnip = subsnip:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ddddaaaattttoooo
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,2 @@
1
+ subsnip
2
+ subsnip_retag
subsnip.py ADDED
@@ -0,0 +1,243 @@
1
+ #!/usr/bin/env python3
2
+ """subsnip: Spotify playlist (Exportify CSV) -> 1:1 official 320k MP3s with Spotify tags, cover and lyrics.
3
+
4
+ Matching, strictest first. Every hit must be an official release (YouTube Music
5
+ track metadata) within MAX_DIFF seconds of the Spotify length:
6
+ 1. ISRC search on YouTube Music (the recording's own ID, so the exact master)
7
+ 2. "artist title" search: artist listed, or exact same title (artist written in another script)
8
+ 3. the artist's own SoundCloud upload, same length
9
+ No match -> failed.txt. Never fan uploads, never a "close enough" version.
10
+
11
+ Re-run safe: songs already downloaded are skipped. Writes <csv name>.m3u8 in playlist order.
12
+ skip.txt in the music folder: songs to never download (see retag.load_skip).
13
+ """
14
+ import argparse, csv, json, os, re, shutil, sys, tempfile, threading, urllib.parse
15
+ from concurrent.futures import ThreadPoolExecutor
16
+ if os.environ.get("YTDLP_PATH"): # e.g. the nightly yt-dlp zipapp, when the system package is too old
17
+ sys.path.insert(0, os.environ["YTDLP_PATH"])
18
+ import yt_dlp
19
+ import subsnip_retag as retag
20
+
21
+ __version__ = "1.0.0"
22
+ BITRATE = "320" # kbps, max MP3 bitrate, ~140 MB per hour of music
23
+ MAX_DIFF = 3 # seconds allowed between Spotify and YouTube Music length
24
+ CANDIDATES = 5
25
+ BASE = {"quiet": True, "no_warnings": True, "noprogress": True, "js_runtimes": {"node": {}},
26
+ **json.loads(os.environ.get("SUBSNIP_YTDLP_OPTS") or "{}")} # extra yt-dlp options as JSON
27
+
28
+
29
+ class RateLimited(Exception):
30
+ pass
31
+
32
+
33
+ def stop_if_rate_limited(e):
34
+ # a rate-limited session makes every lookup fail; stop instead of marking the rest as missing
35
+ if "rate-limited" in str(e):
36
+ raise RateLimited()
37
+
38
+
39
+ def safe(s):
40
+ return re.sub(r'[\\/:*?"<>|]', "_", s).strip(" .")[:120]
41
+
42
+
43
+ def norm(s):
44
+ return re.sub(r"[\W_]", "", s.casefold()) # unicode-aware, so Cyrillic etc. survive
45
+
46
+
47
+ def is_match(info, artist, title, seconds):
48
+ if not info.get("track"): # user uploads / music videos have no track metadata
49
+ return False
50
+ names = [norm(a) for a in (info.get("artists") or [])] + [norm(info.get("channel") or "")]
51
+ same_title = norm(title) != "" and norm(info["track"]) == norm(title) # artist may be spelled in another script
52
+ if norm(artist) not in names and not same_title:
53
+ return False
54
+ return abs((info.get("duration") or 0) - seconds) <= MAX_DIFF
55
+
56
+
57
+ def sc_match(e, artist, seconds):
58
+ """Official SoundCloud upload: posted by the artist's own account, same length."""
59
+ return norm(e.get("uploader") or "") == norm(artist) and abs((e.get("duration") or 0) - seconds) <= MAX_DIFF
60
+
61
+
62
+ def title_hint(found, title):
63
+ """Search result title looks like the song (ignoring "(feat. ...)", " - Remastered" etc.)."""
64
+ t, f = norm(re.sub(r"\(.*?\)|\[.*?\]| - .*", "", title)), norm(found or "")
65
+ return bool(t) and (t in f or (bool(f) and f in t))
66
+
67
+
68
+ def ytm_urls(search, isrc, artist, title):
69
+ seen = set()
70
+ for q, n in ([(isrc, 2)] if isrc else []) + [(f"{artist} {title}", CANDIDATES)]:
71
+ res = search.extract_info(f"https://music.youtube.com/search?q={urllib.parse.quote_plus(q)}#songs", download=False)
72
+ entries = (res.get("entries") or [])[:n]
73
+ entries.sort(key=lambda e: not title_hint(e.get("title"), title)) # likely hits first; none dropped
74
+ for e in entries:
75
+ if e["url"] not in seen:
76
+ seen.add(e["url"])
77
+ yield e["url"]
78
+
79
+
80
+ def find(yt, isrc, artist, title, seconds):
81
+ for url in ytm_urls(yt.search, isrc, artist, title):
82
+ try:
83
+ info = yt.fetch.extract_info(url, download=False)
84
+ except yt_dlp.utils.DownloadError as err:
85
+ stop_if_rate_limited(err)
86
+ continue
87
+ if is_match(info, artist, title, seconds):
88
+ return info
89
+ res = yt.search.extract_info(f"scsearch{CANDIDATES}:{artist} {title}", download=False)
90
+ for e in res.get("entries") or []:
91
+ if sc_match(e, artist, seconds):
92
+ return {**e, "webpage_url": e["url"]}
93
+ return None
94
+
95
+
96
+ _local = threading.local()
97
+
98
+
99
+ def worker_ytdl():
100
+ """One search + one downloader per thread (YoutubeDL is not thread-safe; setting one up per song is slow)."""
101
+ if not hasattr(_local, "fetch"):
102
+ _local.tmp = tempfile.mkdtemp()
103
+ _local.search = yt_dlp.YoutubeDL({**BASE, "extract_flat": True, "playlistend": CANDIDATES})
104
+ _local.fetch = yt_dlp.YoutubeDL({**BASE, "format": "774/141/bestaudio", "outtmpl": os.path.join(_local.tmp, "a.%(ext)s"),
105
+ "postprocessors": [{"key": "FFmpegExtractAudio", "preferredcodec": "mp3",
106
+ "preferredquality": BITRATE}]}) # cover comes from Spotify in retag
107
+ return _local
108
+
109
+
110
+ def song(row, dest, covers, label):
111
+ """Download one row to dest. Returns None on success, else the failed.txt line."""
112
+ title, artists = retag.row_info(row)
113
+ seconds = int(row["Duration (ms)"]) / 1000
114
+ fail = f"{', '.join(artists)} - {title} ({int(seconds)//60}:{int(seconds)%60:02d})"
115
+ yt = worker_ytdl()
116
+ try:
117
+ info = find(yt, row.get("ISRC", "").strip(), artists[0], title, seconds)
118
+ if not info:
119
+ print(f"{label} no exact match, skipped", flush=True)
120
+ return fail
121
+ for f in os.listdir(yt.tmp):
122
+ os.remove(os.path.join(yt.tmp, f))
123
+ yt.fetch.download([info["webpage_url"]])
124
+ except yt_dlp.utils.DownloadError as e:
125
+ stop_if_rate_limited(e)
126
+ print(f"{label} error: {e}", flush=True)
127
+ return fail
128
+ retag.tag(row, os.path.join(yt.tmp, "a.mp3"), dest, covers) # Spotify tags + cover + lyrics
129
+ bad = retag.check(row, dest, covers)
130
+ print(f"{label} ok" if not bad else f"{label} CHECK FAILED: {'; '.join(bad)}", flush=True)
131
+ return None
132
+
133
+
134
+ def write_m3u(path, rows, out, skip):
135
+ with open(path, "w", encoding="utf-8") as f:
136
+ f.write("#EXTM3U\n")
137
+ for row in rows:
138
+ title, artists = retag.row_info(row)
139
+ name = label = f"{artists[0]} - {title}"
140
+ if name in skip:
141
+ if not skip[name]:
142
+ continue
143
+ name = label = skip[name] # your own file: show its name, not the playlist's artist
144
+ else:
145
+ label = f"{', '.join(artists)} - {title}"
146
+ name = safe(name) + ".mp3"
147
+ if os.path.exists(os.path.join(out, name)):
148
+ f.write(f"#EXTINF:{int(row['Duration (ms)']) // 1000},{label}\n{name}\n")
149
+
150
+
151
+ REQUIRED = {"Track URI", "Track Name", "Album Name", "Artist Name(s)", "Release Date", "Duration (ms)"}
152
+ HELP = """\
153
+ subsnip: your playlist as the exact same songs, in 320k MP3.
154
+
155
+ commands:
156
+ download CSV [FOLDER] download the playlist (skips songs you already have)
157
+ check CSV [FOLDER] compare tags and covers with the playlist, change nothing
158
+ retag CSV [FOLDER] rewrite tags, cover and lyrics (audio untouched)
159
+
160
+ CSV: your playlist, exported at https://exportify.net
161
+ FOLDER: where the music goes (default ~/Music/<csv name>)
162
+
163
+ examples:
164
+ subsnip download ~/Downloads/my_playlist.csv
165
+ subsnip download my_playlist.csv ~/Music/player
166
+ subsnip check my_playlist.csv
167
+
168
+ Run "subsnip download -h" for download options.
169
+ Songs it can't match exactly go to FOLDER/failed.txt. Never a fake or a fan upload.
170
+
171
+ made by ddddaaaattttoooo
172
+ """
173
+
174
+
175
+ def main():
176
+ p = argparse.ArgumentParser(prog="subsnip", usage="subsnip {download,check,retag} CSV [FOLDER]",
177
+ description=HELP, formatter_class=argparse.RawDescriptionHelpFormatter, add_help=False)
178
+ p.add_argument("-h", "--help", action="help", help=argparse.SUPPRESS)
179
+ p.add_argument("-V", "--version", action="version", version=f"subsnip {__version__}", help=argparse.SUPPRESS)
180
+ sub = p.add_subparsers(dest="cmd", metavar="")
181
+ cmds = {}
182
+ for name, text in [("download", "download the playlist"), ("check", "compare tags and covers with the playlist"),
183
+ ("retag", "rewrite tags, cover and lyrics")]:
184
+ c = cmds[name] = sub.add_parser(name, help=text, description=text)
185
+ c.add_argument("csv", help="playlist CSV from exportify.net")
186
+ c.add_argument("folder", nargs="?", help="music folder (default ~/Music/<csv name>)")
187
+ d = cmds["download"]
188
+ d.add_argument("--workers", type=int, default=3, help="songs downloaded at once (default 3; more hits YouTube rate limits sooner)")
189
+ a = p.parse_args()
190
+ if not a.cmd:
191
+ sys.exit(HELP)
192
+ if not os.path.isfile(a.csv):
193
+ sys.exit(f"subsnip: no such file: {a.csv}")
194
+ with open(a.csv, encoding="utf-8-sig") as f:
195
+ missing = REQUIRED - set(next(csv.reader(f), []))
196
+ if missing:
197
+ sys.exit(f"subsnip: {a.csv} is not an Exportify CSV (missing: {', '.join(sorted(missing))}). Export it at https://exportify.net")
198
+ for tool in ["ffmpeg", "ffprobe"] + (["node"] if a.cmd == "download" else []):
199
+ if not shutil.which(tool):
200
+ sys.exit(f"subsnip: {tool} not found. Install it first (see README, Requirements)")
201
+ out = a.folder or retag.default_dir(a.csv)
202
+ if a.cmd != "download":
203
+ return retag.run(a.csv, out, a.cmd == "check")
204
+ csv_path = a.csv
205
+ stem = os.path.splitext(os.path.basename(csv_path))[0]
206
+ os.makedirs(out, exist_ok=True)
207
+ rows = [r for r in csv.DictReader(open(csv_path, encoding="utf-8-sig")) if all(retag.row_info(r))]
208
+ covers = tempfile.mkdtemp() # shared Spotify cover cache, separate from per-thread audio dirs
209
+ skip = retag.load_skip(out)
210
+ todo, seen = [], set()
211
+ for i, row in enumerate(rows, 1):
212
+ title, artists = retag.row_info(row)
213
+ dest = os.path.join(out, safe(f"{artists[0]} - {title}") + ".mp3")
214
+ if f"{artists[0]} - {title}" in skip:
215
+ continue
216
+ if not os.path.exists(dest) and dest not in seen: # skip done songs and playlist duplicates
217
+ seen.add(dest)
218
+ todo.append((row, dest, f"[{i}/{len(rows)}] {artists[0]} - {title}"))
219
+ print(f"{len(rows) - len(todo)} already downloaded, {len(todo)} to go", flush=True)
220
+ failed, limited = [], False
221
+ with ThreadPoolExecutor(a.workers) as pool:
222
+ futures = [pool.submit(song, row, dest, covers, label) for row, dest, label in todo]
223
+ for fut in futures:
224
+ try:
225
+ if (r := fut.result()):
226
+ failed.append(r)
227
+ except RateLimited:
228
+ limited = True
229
+ pool.shutdown(cancel_futures=True)
230
+ except Exception as e: # one broken song (cover/lyrics/ffmpeg) must not stop the playlist
231
+ print(" error:", e, flush=True)
232
+ write_m3u(os.path.join(out, f"{stem}.m3u8"), rows, out, skip)
233
+ if failed:
234
+ with open(os.path.join(out, "failed.txt"), "w") as f:
235
+ f.write("\n".join(failed) + "\n")
236
+ print(f"{len(failed)} not found, see {out}/failed.txt")
237
+ if limited:
238
+ sys.exit("YouTube rate limit hit; wait an hour and re-run (finished songs are skipped)")
239
+ print("done")
240
+
241
+
242
+ if __name__ == "__main__":
243
+ main()
subsnip_retag.py ADDED
@@ -0,0 +1,180 @@
1
+ #!/usr/bin/env python3
2
+ """Rewrite tags + cover of downloaded MP3s from the Exportify CSV and Spotify's own album art.
3
+
4
+ Used by `subsnip retag` and `subsnip check`.
5
+ """
6
+ import csv, json, os, re, subprocess, sys, tempfile, time, urllib.error, urllib.parse, urllib.request
7
+ from mutagen.id3 import ID3, SYLT, TCON, TPUB, TSRC, TXXX, USLT
8
+
9
+ _covers = {} # Spotify image id -> local jpg, so one album is fetched once
10
+
11
+
12
+ def safe(s):
13
+ return re.sub(r'[\\/:*?"<>|]', "_", s).strip(" .")[:120]
14
+
15
+
16
+ def load_skip(d):
17
+ """skip.txt in the music folder: "Artist - Title" skips a song; "Artist - Title = Other File" also
18
+ puts Other File.mp3 (your own version) in its place in the playlist. Neither is downloaded or retagged."""
19
+ skip = {}
20
+ p = os.path.join(d, "skip.txt")
21
+ for line in open(p, encoding="utf-8") if os.path.exists(p) else []:
22
+ if line.strip() and not line.startswith("#"):
23
+ name, _, repl = line.partition("=")
24
+ skip[name.strip()] = repl.strip() or None
25
+ return skip
26
+
27
+
28
+ def row_info(row):
29
+ artists = [a.strip() for a in row["Artist Name(s)"].split(";") if a.strip()]
30
+ return row["Track Name"].strip(), artists
31
+
32
+
33
+ def cover(track_uri, tmpdir):
34
+ tid = track_uri.split(":")[-1]
35
+ url = f"https://open.spotify.com/oembed?url=https://open.spotify.com/track/{tid}"
36
+ with urllib.request.urlopen(url, timeout=20) as r:
37
+ thumb = json.load(r)["thumbnail_url"]
38
+ img = thumb.rsplit("/", 1)[1]
39
+ img = "ab67616d0000b273" + img[16:] if img.startswith("ab67616d") else img # 300px id -> 640px id
40
+ if not os.path.exists(_covers.get(img, "")): # cache can point into an already-deleted tmpdir
41
+ path = os.path.join(tmpdir, img + ".jpg")
42
+ urllib.request.urlretrieve(f"https://i.scdn.co/image/{img}", path)
43
+ _covers[img] = path
44
+ time.sleep(0.2)
45
+ return _covers[img]
46
+
47
+
48
+ def lyrics(row):
49
+ """(synced, plain) lyrics from LRCLIB matched on artist/title/album/length; (None, None) if not found."""
50
+ title, artists = row_info(row)
51
+ q = urllib.parse.urlencode({"artist_name": artists[0], "track_name": title, "album_name": row["Album Name"].strip(),
52
+ "duration": round(int(row["Duration (ms)"]) / 1000)})
53
+ req = urllib.request.Request(f"https://lrclib.net/api/get?{q}", headers={"User-Agent": "subsnip/1.0 (https://gitlab.com/ddddaaaattttoooo/subsnip)"})
54
+ try:
55
+ with urllib.request.urlopen(req, timeout=20) as r:
56
+ d = json.load(r)
57
+ except urllib.error.HTTPError as e:
58
+ if e.code != 404:
59
+ raise
60
+ d = search_lyrics(artists[0], title, int(row["Duration (ms)"]) / 1000)
61
+ return d.get("syncedLyrics"), d.get("plainLyrics")
62
+
63
+
64
+ def norm(s):
65
+ return re.sub(r"[^a-z0-9]", "", s.lower())
66
+
67
+
68
+ def search_lyrics(artist, title, seconds):
69
+ """Looser LRCLIB search for when titles differ ("feat." etc); same artist, title and length within 3 s."""
70
+ q = urllib.parse.urlencode({"q": f"{artist} {title}"})
71
+ req = urllib.request.Request(f"https://lrclib.net/api/search?{q}", headers={"User-Agent": "subsnip/1.0 (https://gitlab.com/ddddaaaattttoooo/subsnip)"})
72
+ with urllib.request.urlopen(req, timeout=20) as r:
73
+ hits = json.load(r)
74
+ a, t = norm(artist), norm(re.sub(r"\(.*?\)|\[.*?\]| - .*", "", title))
75
+ ok = [h for h in hits if a in norm(h.get("artistName") or "") and t in norm(h.get("trackName") or "")
76
+ and abs((h.get("duration") or 0) - seconds) <= 3 and not h.get("instrumental")]
77
+ ok.sort(key=lambda h: not h.get("syncedLyrics")) # prefer synced
78
+ return ok[0] if ok else {}
79
+
80
+
81
+ def lrc_lines(synced):
82
+ """[mm:ss.xx]text lines -> [(text, ms)] for the embedded SYLT frame."""
83
+ return [(t.strip(), round((int(m) * 60 + float(sec)) * 1000))
84
+ for m, sec, t in re.findall(r"^\[(\d+):(\d+(?:\.\d+)?)\](.*)$", synced, re.M)]
85
+
86
+
87
+ def add_lyrics(row, path):
88
+ """ISRC/label/genre/explicit tags, plain lyrics (players without synced lyrics),
89
+ embedded synced lyrics (SYLT) and a synced .lrc next to the MP3 (most players with synced lyrics)."""
90
+ synced, plain = lyrics(row)
91
+ tags = ID3(path)
92
+ for frame, value in [(TSRC, row.get("ISRC")), (TPUB, row.get("Record Label")), (TCON, row.get("Genres"))]:
93
+ if (value or "").strip():
94
+ tags.setall(frame.__name__, [frame(encoding=3, text=[v.strip() for v in (value.split(",") if frame is TCON else [value])])])
95
+ if row.get("Explicit") == "true":
96
+ tags.setall("TXXX:ITUNESADVISORY", [TXXX(encoding=3, desc="ITUNESADVISORY", text="1")])
97
+ if synced:
98
+ with open(os.path.splitext(path)[0] + ".lrc", "w", encoding="utf-8") as f:
99
+ f.write(synced + "\n")
100
+ tags.setall("SYLT", [SYLT(encoding=3, lang="eng", format=2, type=1, desc="", text=lrc_lines(synced))])
101
+ if plain or synced:
102
+ text = plain or re.sub(r"^\[[^\]]*\] ?", "", synced, flags=re.M)
103
+ tags.setall("USLT", [USLT(encoding=3, lang="eng", desc="", text=text)])
104
+ tags.save(v2_version=3)
105
+ return bool(synced), bool(plain or synced)
106
+
107
+
108
+ def tag(row, src, dest, tmpdir):
109
+ """Write src audio to dest with Spotify tags and album cover (src may equal dest)."""
110
+ title, artists = row_info(row)
111
+ art = cover(row["Track URI"], tmpdir)
112
+ out = dest + ".tmp.mp3"
113
+ subprocess.run([
114
+ "ffmpeg", "-loglevel", "error", "-y", "-i", src, "-i", art,
115
+ "-map", "0:a", "-map", "1", "-c", "copy", "-map_metadata", "-1", "-id3v2_version", "3",
116
+ "-metadata", f"title={title}", "-metadata", f"artist={', '.join(artists)}",
117
+ "-metadata", f"album_artist={artists[0]}", "-metadata", f"album={row['Album Name'].strip()}",
118
+ "-metadata", f"date={row['Release Date'][:4]}",
119
+ "-metadata:s:v", "title=Album cover", "-metadata:s:v", "comment=Cover (front)",
120
+ out,
121
+ ], check=True)
122
+ os.replace(out, dest)
123
+ return add_lyrics(row, dest)
124
+
125
+
126
+ def check(row, path, tmpdir):
127
+ """Return list of problems: tags differ from CSV or cover differs from Spotify's image."""
128
+ title, artists = row_info(row)
129
+ want = {"title": title, "artist": ", ".join(artists), "album_artist": artists[0],
130
+ "album": row["Album Name"].strip(), "date": row["Release Date"][:4]}
131
+ probe = json.loads(subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format_tags", "-of", "json", path],
132
+ capture_output=True, text=True, check=True).stdout)
133
+ have = {k.lower(): v for k, v in probe.get("format", {}).get("tags", {}).items()}
134
+ bad = [f"{k}: {have.get(k)!r} != {v!r}" for k, v in want.items() if have.get(k) != v]
135
+ embedded = subprocess.run(["ffmpeg", "-loglevel", "error", "-i", path, "-map", "0:v", "-c", "copy", "-f", "image2pipe", "-"],
136
+ capture_output=True).stdout
137
+ if embedded != open(cover(row["Track URI"], tmpdir), "rb").read():
138
+ bad.append("cover differs from Spotify")
139
+ return bad
140
+
141
+
142
+ def default_dir(csv_path):
143
+ return os.path.expanduser(f"~/Music/{os.path.splitext(os.path.basename(csv_path))[0]}")
144
+
145
+
146
+ def run(csv_path, d, checking):
147
+ """Retag (or with checking, only verify) every downloaded song of the CSV in folder d."""
148
+ done = 0
149
+ skip = load_skip(d)
150
+ with tempfile.TemporaryDirectory() as tmp:
151
+ for row in csv.DictReader(open(csv_path, encoding="utf-8-sig")):
152
+ title, artists = row_info(row)
153
+ if not title or not artists:
154
+ continue
155
+ if f"{artists[0]} - {title}" in skip:
156
+ continue
157
+ p = os.path.join(d, safe(f"{artists[0]} - {title}") + ".mp3")
158
+ if not os.path.exists(p):
159
+ continue
160
+ try:
161
+ if checking:
162
+ for b in check(row, p, tmp):
163
+ print(f"BAD {os.path.basename(p)}: {b}", flush=True)
164
+ else:
165
+ synced, any_ = tag(row, p, p, tmp)
166
+ if not any_:
167
+ print(f"no lyrics: {os.path.basename(p)}", flush=True)
168
+ elif not synced:
169
+ print(f"plain lyrics only: {os.path.basename(p)}", flush=True)
170
+ done += 1
171
+ except Exception as e: # keep going; the file is untouched if ffmpeg/cover failed
172
+ print(f"failed: {p}: {e}", flush=True)
173
+ print(f"{'checked' if checking else 'retagged'} {done}")
174
+
175
+
176
+ if __name__ == "__main__":
177
+ checking = sys.argv[1] == "--check"
178
+ if checking:
179
+ sys.argv.pop(1)
180
+ run(sys.argv[1], sys.argv[2] if len(sys.argv) > 2 else default_dir(sys.argv[1]), checking)