zhuk 0.1.0__tar.gz

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.

Potentially problematic release.


This version of zhuk might be problematic. Click here for more details.

zhuk-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,10 @@
1
+ Metadata-Version: 2.3
2
+ Name: zhuk
3
+ Version: 0.1.0
4
+ Summary: Download Spotify tracks and playlists as MP3 from YouTube
5
+ Requires-Dist: mutagen>=1.47.0
6
+ Requires-Dist: spotipy>=2.26.0
7
+ Requires-Dist: yt-dlp>=2026.3.13
8
+ Requires-Dist: python-dotenv>=1.2.2
9
+ Requires-Dist: rapidfuzz>=3.0.0
10
+ Requires-Python: >=3.10
@@ -0,0 +1,25 @@
1
+ [build-system]
2
+ requires = ["uv_build>=0.10.10,<0.11.0"]
3
+ build-backend = "uv_build"
4
+
5
+ [project]
6
+ name = "zhuk"
7
+ version = "0.1.0"
8
+ description = "Download Spotify tracks and playlists as MP3 from YouTube"
9
+ requires-python = ">=3.10"
10
+ dependencies = [
11
+ "mutagen>=1.47.0",
12
+ "spotipy>=2.26.0",
13
+ "yt-dlp>=2026.3.13",
14
+ "python-dotenv>=1.2.2",
15
+ "rapidfuzz>=3.0.0",
16
+ ]
17
+
18
+ [project.scripts]
19
+ zhuk = "zhuk.main:main"
20
+
21
+ [dependency-groups]
22
+ dev = [
23
+ "pytest>=8.0",
24
+ "pytest-mock>=3.14",
25
+ ]
@@ -0,0 +1 @@
1
+ """zhuk – download Spotify tracks and playlists as MP3 from YouTube."""
@@ -0,0 +1,89 @@
1
+ """YouTube search and MP3 download via yt-dlp."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+
7
+ import mutagen.id3
8
+ import yt_dlp
9
+
10
+ from zhuk.spotify import TrackInfo
11
+
12
+ _DEFAULT_OUTPUT_DIR = "downloads"
13
+
14
+
15
+ def write_id3_tags(mp3_path: str, track: TrackInfo) -> None:
16
+ """Embed ID3 title, artist and album tags into an MP3 file."""
17
+ try:
18
+ tags = mutagen.id3.ID3(mp3_path)
19
+ except mutagen.id3.ID3NoHeaderError:
20
+ tags = mutagen.id3.ID3()
21
+
22
+ tags["TIT2"] = mutagen.id3.TIT2(encoding=3, text=track.title)
23
+ tags["TPE1"] = mutagen.id3.TPE1(encoding=3, text=track.artist)
24
+ if track.album:
25
+ tags["TALB"] = mutagen.id3.TALB(encoding=3, text=track.album)
26
+
27
+ tags.save(mp3_path)
28
+
29
+
30
+ def download_track(track: TrackInfo, output_dir: str = _DEFAULT_OUTPUT_DIR) -> str:
31
+ """Search YouTube for *track* and download the best match as an MP3.
32
+
33
+ Parameters
34
+ ----------
35
+ track:
36
+ Metadata for the song to download.
37
+ output_dir:
38
+ Directory where the MP3 file will be saved. Created automatically
39
+ if it does not already exist.
40
+
41
+ Returns
42
+ -------
43
+ str
44
+ Absolute path to the downloaded MP3 file.
45
+ """
46
+ os.makedirs(output_dir, exist_ok=True)
47
+
48
+ output_template = os.path.join(output_dir, "%(title)s.%(ext)s")
49
+
50
+ ydl_opts = {
51
+ "format": "bestaudio/best",
52
+ "outtmpl": output_template,
53
+ "quiet": True,
54
+ "no_warnings": True,
55
+ "postprocessors": [
56
+ {
57
+ "key": "FFmpegExtractAudio",
58
+ "preferredcodec": "mp3",
59
+ "preferredquality": "192",
60
+ }
61
+ ],
62
+ "default_search": "ytsearch1",
63
+ "noplaylist": True,
64
+ }
65
+
66
+ query = track.search_query()
67
+ with yt_dlp.YoutubeDL(ydl_opts) as ydl:
68
+ info = ydl.extract_info(query, download=True)
69
+ if "entries" in info:
70
+ info = info["entries"][0]
71
+ filename = ydl.prepare_filename(info)
72
+ # yt-dlp replaces the extension after post-processing
73
+ base, _ = os.path.splitext(filename)
74
+ mp3_path = base + ".mp3"
75
+
76
+ mp3_path = os.path.abspath(mp3_path)
77
+ write_id3_tags(mp3_path, track)
78
+ return mp3_path
79
+
80
+
81
+ def download_tracks(
82
+ tracks: list[TrackInfo], output_dir: str = _DEFAULT_OUTPUT_DIR
83
+ ) -> list[str]:
84
+ """Download each track in *tracks* and return their MP3 paths."""
85
+ paths: list[str] = []
86
+ for track in tracks:
87
+ path = download_track(track, output_dir=output_dir)
88
+ paths.append(path)
89
+ return paths
@@ -0,0 +1,98 @@
1
+ """CLI entry point for zhuk."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+
8
+ from zhuk.downloader import download_track, download_tracks
9
+ from zhuk.matcher import find_missing_tracks
10
+ from zhuk.spotify import get_playlist, get_track
11
+
12
+ TRACK_URL_HINT = "open.spotify.com/track/"
13
+ PLAYLIST_URL_HINT = "open.spotify.com/playlist/"
14
+
15
+
16
+ def main(argv: list[str] | None = None) -> None:
17
+ parser = argparse.ArgumentParser(
18
+ prog="zhuk",
19
+ description="Download a Spotify track or playlist as MP3 from YouTube.",
20
+ )
21
+ parser.add_argument(
22
+ "url",
23
+ help="Spotify track or playlist URL",
24
+ )
25
+ parser.add_argument(
26
+ "-o",
27
+ "--output",
28
+ default="downloads",
29
+ metavar="DIR",
30
+ help="Directory to save MP3 files (default: downloads)",
31
+ )
32
+ parser.add_argument(
33
+ "--sync",
34
+ action="store_true",
35
+ help="Sync mode: only download tracks not already present locally",
36
+ )
37
+ args = parser.parse_args(argv)
38
+
39
+ url: str = args.url
40
+ output_dir: str = args.output
41
+ sync_mode: bool = args.sync
42
+
43
+ if PLAYLIST_URL_HINT in url:
44
+ print(f"Fetching playlist from Spotify…")
45
+ tracks = get_playlist(url)
46
+ print(f"Found {len(tracks)} track(s) in playlist.")
47
+
48
+ if sync_mode:
49
+ print(f"Scanning {output_dir} for existing tracks…")
50
+ missing_tracks, matched_tracks = find_missing_tracks(tracks, output_dir, threshold=90)
51
+
52
+ print(f" ✓ {len(matched_tracks)} track(s) already present")
53
+ print(f" → {len(missing_tracks)} track(s) to download")
54
+
55
+ if missing_tracks:
56
+ print(f"Starting download…")
57
+ paths = download_tracks(missing_tracks, output_dir=output_dir)
58
+ for path in paths:
59
+ print(f" ✓ {path}")
60
+ else:
61
+ print("All tracks are already present. Nothing to download.")
62
+ else:
63
+ print(f"Starting download…")
64
+ paths = download_tracks(tracks, output_dir=output_dir)
65
+ for path in paths:
66
+ print(f" ✓ {path}")
67
+ elif TRACK_URL_HINT in url:
68
+ print(f"Fetching track from Spotify…")
69
+ track = get_track(url)
70
+ assert track is not None
71
+
72
+ if sync_mode:
73
+ print(f"Scanning {output_dir} for existing tracks…")
74
+ missing_tracks, matched_tracks = find_missing_tracks([track], output_dir, threshold=90)
75
+
76
+ if matched_tracks:
77
+ print(f" ✓ Track already present: {matched_tracks[0][1].filepath}")
78
+ print("Nothing to download.")
79
+ else:
80
+ print(f"Downloading: {track.search_query()}")
81
+ path = download_track(track, output_dir=output_dir)
82
+ print(f" ✓ {path}")
83
+ else:
84
+ print(f"Downloading: {track.search_query()}")
85
+ path = download_track(track, output_dir=output_dir)
86
+ print(f" ✓ {path}")
87
+ else:
88
+ print(
89
+ "Error: URL must be a Spotify track or playlist URL.\n"
90
+ " Track: https://open.spotify.com/track/<id>\n"
91
+ " Playlist: https://open.spotify.com/playlist/<id>",
92
+ file=sys.stderr,
93
+ )
94
+ sys.exit(1)
95
+
96
+
97
+ if __name__ == "__main__":
98
+ main()
@@ -0,0 +1,148 @@
1
+ """Fuzzy matching of Spotify tracks against local MP3 files."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from dataclasses import dataclass
7
+
8
+ import mutagen.id3
9
+ from rapidfuzz import fuzz
10
+
11
+ from zhuk.spotify import TrackInfo
12
+
13
+
14
+ @dataclass
15
+ class LocalTrack:
16
+ """Metadata from a local MP3 file."""
17
+
18
+ filepath: str
19
+ title: str
20
+ artist: str
21
+
22
+ def normalized_string(self) -> str:
23
+ """Return a normalized string for fuzzy matching."""
24
+ return f"{self.artist} - {self.title}".lower().strip()
25
+
26
+
27
+ def scan_mp3_files(directory: str) -> list[str]:
28
+ """Return a list of MP3 file paths in the given directory (non-recursive)."""
29
+ if not os.path.exists(directory):
30
+ return []
31
+
32
+ mp3_files = []
33
+ try:
34
+ for filename in os.listdir(directory):
35
+ if filename.lower().endswith(".mp3"):
36
+ mp3_files.append(os.path.join(directory, filename))
37
+ except (OSError, PermissionError):
38
+ pass
39
+
40
+ return mp3_files
41
+
42
+
43
+ def read_id3_tags(filepath: str) -> LocalTrack | None:
44
+ """Read artist and title from MP3 ID3 tags.
45
+
46
+ Returns None if tags cannot be read or are missing.
47
+ """
48
+ try:
49
+ tags = mutagen.id3.ID3(filepath)
50
+ title = str(tags.get("TIT2", [""])[0]) if "TIT2" in tags else ""
51
+ artist = str(tags.get("TPE1", [""])[0]) if "TPE1" in tags else ""
52
+
53
+ if title and artist:
54
+ return LocalTrack(filepath=filepath, title=title, artist=artist)
55
+ except (mutagen.id3.ID3NoHeaderError, Exception):
56
+ pass
57
+
58
+ return None
59
+
60
+
61
+ def match_track(
62
+ spotify_track: TrackInfo, local_tracks: list[LocalTrack], threshold: int = 90
63
+ ) -> LocalTrack | None:
64
+ """Find the best matching local track for a Spotify track.
65
+
66
+ Uses fuzzy string matching on normalized "artist - title" strings.
67
+ Returns the best match if similarity >= threshold, otherwise None.
68
+
69
+ Parameters
70
+ ----------
71
+ spotify_track:
72
+ The Spotify track to match.
73
+ local_tracks:
74
+ List of local tracks to match against.
75
+ threshold:
76
+ Minimum similarity score (0-100) to consider a match.
77
+
78
+ Returns
79
+ -------
80
+ LocalTrack | None
81
+ The best matching local track, or None if no match found.
82
+ """
83
+ if not local_tracks:
84
+ return None
85
+
86
+ spotify_str = f"{spotify_track.artist} - {spotify_track.title}".lower().strip()
87
+
88
+ best_match = None
89
+ best_score = 0
90
+
91
+ for local_track in local_tracks:
92
+ local_str = local_track.normalized_string()
93
+ score = fuzz.ratio(spotify_str, local_str)
94
+
95
+ if score > best_score:
96
+ best_score = score
97
+ best_match = local_track
98
+
99
+ if best_score >= threshold:
100
+ return best_match
101
+
102
+ return None
103
+
104
+
105
+ def find_missing_tracks(
106
+ spotify_tracks: list[TrackInfo], local_dir: str, threshold: int = 90
107
+ ) -> tuple[list[TrackInfo], list[tuple[TrackInfo, LocalTrack]]]:
108
+ """Find which Spotify tracks are missing from the local directory.
109
+
110
+ Scans the local directory for MP3 files, reads their ID3 tags,
111
+ and performs fuzzy matching against the Spotify track list.
112
+
113
+ Parameters
114
+ ----------
115
+ spotify_tracks:
116
+ List of tracks from Spotify to check.
117
+ local_dir:
118
+ Local directory to scan for MP3 files.
119
+ threshold:
120
+ Minimum similarity score (0-100) for fuzzy matching.
121
+
122
+ Returns
123
+ -------
124
+ tuple[list[TrackInfo], list[tuple[TrackInfo, LocalTrack]]]
125
+ A tuple of (missing_tracks, matched_tracks).
126
+ - missing_tracks: Spotify tracks not found locally
127
+ - matched_tracks: List of (Spotify track, matched local track) pairs
128
+ """
129
+ # Scan local directory and read ID3 tags
130
+ mp3_files = scan_mp3_files(local_dir)
131
+ local_tracks = []
132
+ for mp3_file in mp3_files:
133
+ local_track = read_id3_tags(mp3_file)
134
+ if local_track:
135
+ local_tracks.append(local_track)
136
+
137
+ # Match each Spotify track
138
+ missing_tracks = []
139
+ matched_tracks = []
140
+
141
+ for spotify_track in spotify_tracks:
142
+ match = match_track(spotify_track, local_tracks, threshold)
143
+ if match:
144
+ matched_tracks.append((spotify_track, match))
145
+ else:
146
+ missing_tracks.append(spotify_track)
147
+
148
+ return missing_tracks, matched_tracks
@@ -0,0 +1,61 @@
1
+ """Spotify API helpers for retrieving track and playlist metadata."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+
7
+ import spotipy
8
+ from dotenv import load_dotenv
9
+ from spotipy.oauth2 import SpotifyOAuth
10
+
11
+ load_dotenv()
12
+
13
+
14
+ @dataclass
15
+ class TrackInfo:
16
+ """Minimal information about a Spotify track needed to find it on YouTube."""
17
+
18
+ title: str
19
+ artist: str
20
+ album: str = ""
21
+
22
+ def search_query(self) -> str:
23
+ """Return a YouTube search query for this track."""
24
+ return f"{self.artist} - {self.title}"
25
+
26
+
27
+ def build_client() -> spotipy.Spotify:
28
+ auth_manager = SpotifyOAuth(scope=["playlist-read-private", "playlist-read-collaborative"])
29
+ return spotipy.Spotify(auth_manager=auth_manager)
30
+
31
+
32
+ def get_track(url: str) -> TrackInfo | None:
33
+ """Return :class:`TrackInfo` for a Spotify track URL."""
34
+ sp = build_client()
35
+ data = sp.track(url)
36
+ if data is not None:
37
+ title = data["name"]
38
+ artist = data["artists"][0]["name"]
39
+ album = data["album"]["name"]
40
+ return TrackInfo(title=title, artist=artist, album=album)
41
+ return None
42
+
43
+
44
+ def get_playlist(url: str) -> list[TrackInfo]:
45
+ """Return a list of :class:`TrackInfo` for every track in a Spotify playlist."""
46
+ sp = build_client()
47
+ tracks: list[TrackInfo] = []
48
+
49
+ results = sp.playlist_tracks(url)
50
+ while results:
51
+ for item in results["items"]:
52
+ track = item.get("item")
53
+ if track is None:
54
+ continue
55
+ title = track["name"]
56
+ artist = track["artists"][0]["name"]
57
+ album = track["album"]["name"]
58
+ tracks.append(TrackInfo(title=title, artist=artist, album=album))
59
+ results = sp.next(results) if results.get("next") else None
60
+
61
+ return tracks