pyopenaudio 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,224 @@
1
+ from pathlib import Path
2
+ from typing import Callable, Optional
3
+ import yt_dlp
4
+
5
+ from openaudio.core.downloader import AudioDownloader
6
+ from openaudio.core.lyrics import LyricsFetcher
7
+ from openaudio.core.matcher import AudioMatcher
8
+ from openaudio.core.models import (
9
+ DownloadOptions,
10
+ DownloadProgress,
11
+ PlaylistInfo,
12
+ TrackMetadata,
13
+ TrackStatus,
14
+ )
15
+ from openaudio.core.sequencer import Sequencer
16
+ from openaudio.core.spotify import SpotifyExtractor
17
+ from openaudio.core.tagger import AudioTagger
18
+ from openaudio.core.youtube import YouTubeExtractor
19
+
20
+ class DownloadPipeline:
21
+
22
+ @classmethod
23
+ def resolve_input(
24
+ cls,
25
+ query_or_url: str,
26
+ spotify_client_id: str = "",
27
+ spotify_client_secret: str = "",
28
+ ) -> PlaylistInfo:
29
+ query = query_or_url.strip()
30
+
31
+ if SpotifyExtractor.is_spotify_url(query):
32
+ return SpotifyExtractor.get_metadata(
33
+ query,
34
+ client_id=spotify_client_id,
35
+ client_secret=spotify_client_secret,
36
+ )
37
+
38
+ if YouTubeExtractor.is_youtube_url(query):
39
+ return YouTubeExtractor.get_metadata(query)
40
+
41
+ return cls._resolve_search_query(query)
42
+
43
+ @classmethod
44
+ def _resolve_search_query(cls, query: str) -> PlaylistInfo:
45
+ ydl_opts = {
46
+ "extract_flat": True,
47
+ "skip_download": True,
48
+ "quiet": True,
49
+ "no_warnings": True,
50
+ "geo_bypass": True,
51
+ "extractor_args": {
52
+ "youtube": {
53
+ "player_client": ["android_music", "android", "mweb", "web"],
54
+ }
55
+ },
56
+ }
57
+
58
+ with yt_dlp.YoutubeDL(ydl_opts) as ydl:
59
+ res = ydl.extract_info(f"ytsearch1:{query}", download=False)
60
+ if not res or "entries" not in res or not res["entries"]:
61
+ raise ValueError(f"No search results found for query: '{query}'")
62
+
63
+ entry = res["entries"][0]
64
+ title = entry.get("title") or query
65
+ uploader = entry.get("uploader") or entry.get("channel") or "Unknown Artist"
66
+ duration = entry.get("duration", 0) or 0
67
+ thumb = entry.get("thumbnail")
68
+ vid = entry.get("id")
69
+ v_url = entry.get("url") or (f"https://www.youtube.com/watch?v={vid}" if vid else None)
70
+
71
+ artist = uploader
72
+ song_title = title
73
+ if " - " in title:
74
+ parts = title.split(" - ", 1)
75
+ artist = parts[0].strip()
76
+ song_title = parts[1].strip()
77
+
78
+ track = TrackMetadata(
79
+ title=song_title,
80
+ artists=[artist],
81
+ album="Single",
82
+ album_artist=artist,
83
+ duration_seconds=float(duration),
84
+ track_number=1,
85
+ total_tracks=1,
86
+ cover_url=thumb,
87
+ source_url=v_url or query,
88
+ source_id=vid,
89
+ source_provider="search",
90
+ youtube_id=vid,
91
+ youtube_url=v_url,
92
+ )
93
+
94
+ return PlaylistInfo(
95
+ title=song_title,
96
+ author=artist,
97
+ cover_url=thumb,
98
+ tracks=[track],
99
+ source_url=v_url or query,
100
+ source_type="search",
101
+ )
102
+
103
+ @classmethod
104
+ def process_track(
105
+ cls,
106
+ track: TrackMetadata,
107
+ options: DownloadOptions,
108
+ folder_name: str = "",
109
+ total_tracks: int = 1,
110
+ index: int = 1,
111
+ progress_callback: Optional[Callable[[DownloadProgress], None]] = None,
112
+ ) -> Path:
113
+ dest_path = Sequencer.get_destination_path(
114
+ track,
115
+ options,
116
+ folder_name=folder_name,
117
+ total_tracks=total_tracks,
118
+ index=index,
119
+ )
120
+
121
+ if dest_path.exists() and dest_path.stat().st_size < 100_000:
122
+ try:
123
+ dest_path.unlink()
124
+ except Exception:
125
+ pass
126
+
127
+ if dest_path.exists() and not options.overwrite and dest_path.stat().st_size >= 100_000:
128
+ if progress_callback:
129
+ progress_callback(
130
+ DownloadProgress(
131
+ current_track_idx=index,
132
+ total_tracks=total_tracks,
133
+ track_title=track.title,
134
+ status=TrackStatus.SKIPPED,
135
+ download_percent=100.0,
136
+ output_path=dest_path,
137
+ )
138
+ )
139
+ return dest_path
140
+
141
+ if progress_callback:
142
+ progress_callback(
143
+ DownloadProgress(
144
+ current_track_idx=index,
145
+ total_tracks=total_tracks,
146
+ track_title=track.title,
147
+ status=TrackStatus.MATCHING,
148
+ )
149
+ )
150
+
151
+ def wrapped_callback(p: DownloadProgress):
152
+ if p.current_track_idx == 0:
153
+ p.current_track_idx = index
154
+ if p.total_tracks == 0:
155
+ p.total_tracks = total_tracks
156
+ if progress_callback:
157
+ progress_callback(p)
158
+
159
+ candidates = AudioMatcher.get_ranked_candidates(track)
160
+ if not candidates:
161
+ raise RuntimeError(f"No audio candidates found on YouTube for '{track.artist_str} - {track.title}'")
162
+
163
+ download_succeeded = False
164
+ last_error = None
165
+ for candidate_url, score in candidates[:5]:
166
+ try:
167
+ AudioDownloader.download_audio(
168
+ track,
169
+ dest_path,
170
+ options,
171
+ stream_url=candidate_url,
172
+ progress_callback=wrapped_callback,
173
+ track_index=index,
174
+ total_tracks=total_tracks,
175
+ )
176
+ if dest_path.exists() and dest_path.stat().st_size >= 100_000:
177
+ track.youtube_url = candidate_url
178
+ if "v=" in candidate_url:
179
+ track.youtube_id = candidate_url.split("v=")[1].split("&")[0]
180
+ download_succeeded = True
181
+ break
182
+ except Exception as e:
183
+ last_error = e
184
+ if dest_path.exists():
185
+ dest_path.unlink(missing_ok=True)
186
+ continue
187
+
188
+ if not download_succeeded or not dest_path.exists() or dest_path.stat().st_size < 100_000:
189
+ if dest_path.exists():
190
+ dest_path.unlink(missing_ok=True)
191
+ raise RuntimeError(f"Failed to download audio for '{track.title}': {last_error}")
192
+
193
+ plain_lyrics = None
194
+ if options.fetch_lyrics:
195
+ plain_lyrics, synced_lyrics = LyricsFetcher.fetch_lyrics(track)
196
+ if synced_lyrics and options.save_lrc:
197
+ LyricsFetcher.save_lrc_file(synced_lyrics, dest_path)
198
+
199
+ if progress_callback:
200
+ progress_callback(
201
+ DownloadProgress(
202
+ current_track_idx=index,
203
+ total_tracks=total_tracks,
204
+ track_title=track.title,
205
+ status=TrackStatus.TAGGING,
206
+ download_percent=100.0,
207
+ )
208
+ )
209
+
210
+ AudioTagger.tag_file(dest_path, track, lyrics=plain_lyrics)
211
+
212
+ if progress_callback:
213
+ progress_callback(
214
+ DownloadProgress(
215
+ current_track_idx=index,
216
+ total_tracks=total_tracks,
217
+ track_title=track.title,
218
+ status=TrackStatus.COMPLETED,
219
+ download_percent=100.0,
220
+ output_path=dest_path,
221
+ )
222
+ )
223
+
224
+ return dest_path
@@ -0,0 +1,44 @@
1
+ from pathlib import Path
2
+
3
+ from openaudio.core.models import DownloadOptions, TrackMetadata
4
+ from openaudio.utils.formatting import pad_number, sanitize_filename
5
+
6
+ class Sequencer:
7
+
8
+ @classmethod
9
+ def generate_filename(
10
+ cls,
11
+ track: TrackMetadata,
12
+ options: DownloadOptions,
13
+ total_tracks: int = 1,
14
+ index: int = 1,
15
+ ) -> str:
16
+ ext = options.format.lower().lstrip(".")
17
+ artist_clean = sanitize_filename(track.primary_artist)
18
+ title_clean = sanitize_filename(track.title)
19
+
20
+ padded_idx = pad_number(index, total_tracks, min_digits=3)
21
+ name = f"{padded_idx} - {title_clean} - {artist_clean}.{ext}"
22
+ return sanitize_filename(name)
23
+
24
+ @classmethod
25
+ def get_destination_path(
26
+ cls,
27
+ track: TrackMetadata,
28
+ options: DownloadOptions,
29
+ folder_name: str = "",
30
+ total_tracks: int = 1,
31
+ index: int = 1,
32
+ ) -> Path:
33
+ base_dir = options.output_dir
34
+
35
+ if folder_name:
36
+ clean_folder = sanitize_filename(folder_name)
37
+ target_dir = base_dir / clean_folder
38
+ else:
39
+ target_dir = base_dir
40
+
41
+ target_dir.mkdir(parents=True, exist_ok=True)
42
+
43
+ filename = cls.generate_filename(track, options, total_tracks=total_tracks, index=index)
44
+ return target_dir / filename