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.
openaudio/__init__.py ADDED
@@ -0,0 +1,50 @@
1
+
2
+ __version__ = "1.0.0"
3
+
4
+ from .core.config import get_download_options, load_config, save_config
5
+ from .main import main, normalize_quality, parse_args
6
+ from .ui.cli import execute_download, run_diagnostics
7
+ from .ui.tui import run_interactive_tui
8
+ from .utils.formatting import (
9
+ clean_artist_name,
10
+ format_bytes,
11
+ format_duration,
12
+ pad_number,
13
+ sanitize_filename,
14
+ )
15
+ from .utils.system import (
16
+ check_internet_connection,
17
+ get_default_music_dir,
18
+ get_ffmpeg_install_instructions,
19
+ get_ffmpeg_path,
20
+ get_platform_name,
21
+ is_ffmpeg_available,
22
+ is_narrow_screen,
23
+ is_termux,
24
+ )
25
+
26
+ __all__ = [
27
+ "__version__",
28
+ "check_internet_connection",
29
+ "clean_artist_name",
30
+ "execute_download",
31
+ "format_bytes",
32
+ "format_duration",
33
+ "get_default_music_dir",
34
+ "get_download_options",
35
+ "get_ffmpeg_install_instructions",
36
+ "get_ffmpeg_path",
37
+ "get_platform_name",
38
+ "is_ffmpeg_available",
39
+ "is_narrow_screen",
40
+ "is_termux",
41
+ "load_config",
42
+ "main",
43
+ "normalize_quality",
44
+ "pad_number",
45
+ "parse_args",
46
+ "run_diagnostics",
47
+ "run_interactive_tui",
48
+ "sanitize_filename",
49
+ "save_config",
50
+ ]
@@ -0,0 +1,80 @@
1
+ import json
2
+ import os
3
+ from pathlib import Path
4
+ from typing import Any, Dict
5
+
6
+ from openaudio.core.models import DownloadOptions
7
+ from openaudio.utils.system import get_default_music_dir
8
+
9
+ CONFIG_DIR = Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config")) / "openaudio"
10
+ CONFIG_FILE = CONFIG_DIR / "config.json"
11
+
12
+ DEFAULT_CONFIG: Dict[str, Any] = {
13
+ "format": "mp3",
14
+ "bitrate": "320k",
15
+ "output_dir": str(get_default_music_dir()),
16
+ "sequential_naming": True,
17
+ "naming_template": "{index:03d} - {title} - {artist}",
18
+ "fetch_lyrics": True,
19
+ "save_lrc": False,
20
+ "embed_cover": True,
21
+ "overwrite": False,
22
+ "max_retries": 3,
23
+ "rate_limit_delay": 1.2,
24
+ "mobile_mode": False,
25
+ "concurrent_downloads": 3,
26
+ "spotify_client_id": "",
27
+ "spotify_client_secret": "",
28
+ }
29
+
30
+ def load_config() -> Dict[str, Any]:
31
+ if not CONFIG_FILE.exists():
32
+ save_config(DEFAULT_CONFIG)
33
+ return dict(DEFAULT_CONFIG)
34
+
35
+ try:
36
+ with open(CONFIG_FILE, "r", encoding="utf-8") as f:
37
+ data = json.load(f)
38
+ config = dict(DEFAULT_CONFIG)
39
+ config.update(data)
40
+ return config
41
+ except Exception:
42
+ return dict(DEFAULT_CONFIG)
43
+
44
+ def save_config(config: Dict[str, Any]) -> None:
45
+ try:
46
+ CONFIG_DIR.mkdir(parents=True, exist_ok=True)
47
+ with open(CONFIG_FILE, "w", encoding="utf-8") as f:
48
+ json.dump(config, f, indent=2)
49
+ except Exception:
50
+ local_cfg = Path.cwd() / "openaudio_config.json"
51
+ with open(local_cfg, "w", encoding="utf-8") as f:
52
+ json.dump(config, f, indent=2)
53
+
54
+ def get_download_options(overrides: Dict[str, Any] | None = None) -> DownloadOptions:
55
+ cfg = load_config()
56
+ if overrides:
57
+ cfg.update({k: v for k, v in overrides.items() if v is not None})
58
+
59
+ out_dir = Path(cfg.get("output_dir", str(get_default_music_dir()))).expanduser()
60
+
61
+ try:
62
+ concurrent_val = max(1, min(5, int(cfg.get("concurrent_downloads", 3))))
63
+ except Exception:
64
+ concurrent_val = 3
65
+
66
+ return DownloadOptions(
67
+ format=cfg.get("format", "mp3"),
68
+ bitrate=cfg.get("bitrate", "320k"),
69
+ output_dir=out_dir,
70
+ sequential_naming=cfg.get("sequential_naming", True),
71
+ naming_template=cfg.get("naming_template", "{index:03d} - {title} - {artist}"),
72
+ fetch_lyrics=cfg.get("fetch_lyrics", True),
73
+ save_lrc=cfg.get("save_lrc", False),
74
+ embed_cover=cfg.get("embed_cover", True),
75
+ overwrite=cfg.get("overwrite", False),
76
+ max_retries=cfg.get("max_retries", 3),
77
+ rate_limit_delay=float(cfg.get("rate_limit_delay", 1.2)),
78
+ mobile_mode=cfg.get("mobile_mode", False),
79
+ concurrent_downloads=concurrent_val,
80
+ )
@@ -0,0 +1,165 @@
1
+ import random
2
+ import shutil
3
+ import tempfile
4
+ import time
5
+ from pathlib import Path
6
+ from typing import Callable, Optional
7
+ import yt_dlp
8
+
9
+ from openaudio.core.models import DownloadOptions, DownloadProgress, TrackMetadata, TrackStatus
10
+
11
+ class AudioDownloader:
12
+
13
+ CLIENT_PROFILES = [
14
+ ["android_music", "android", "mweb"],
15
+ ["android"],
16
+ ["web"],
17
+ ]
18
+
19
+ @classmethod
20
+ def download_audio(
21
+ cls,
22
+ track: TrackMetadata,
23
+ dest_path: Path,
24
+ options: DownloadOptions,
25
+ stream_url: Optional[str] = None,
26
+ progress_callback: Optional[Callable[[DownloadProgress], None]] = None,
27
+ track_index: int = 1,
28
+ total_tracks: int = 1,
29
+ ) -> Path:
30
+ url_to_download = stream_url or track.youtube_url
31
+ if not url_to_download:
32
+ raise ValueError(f"No stream URL attached to track: {track.title}")
33
+
34
+ if dest_path.exists() and not options.overwrite and dest_path.stat().st_size > 100_000:
35
+ if progress_callback:
36
+ prog = DownloadProgress(
37
+ current_track_idx=track_index,
38
+ total_tracks=total_tracks,
39
+ track_title=track.title,
40
+ status=TrackStatus.SKIPPED,
41
+ download_percent=100.0,
42
+ output_path=dest_path,
43
+ )
44
+ progress_callback(prog)
45
+ return dest_path
46
+
47
+ temp_dir = Path(tempfile.mkdtemp(prefix="openaudio_"))
48
+ temp_out_template = str(temp_dir / "%(id)s.%(ext)s")
49
+
50
+ fmt = options.format.lower()
51
+ if fmt == "mp3":
52
+ preferred_quality = options.bitrate.replace("k", "") if options.bitrate else "320"
53
+ elif fmt == "opus":
54
+ preferred_quality = "160"
55
+ elif fmt in ("flac", "wav"):
56
+ preferred_quality = "0"
57
+ else:
58
+ preferred_quality = "256"
59
+
60
+ def yt_hook(d: dict):
61
+ if not progress_callback:
62
+ return
63
+
64
+ status = d.get("status")
65
+ if status == "downloading":
66
+ total_bytes = d.get("total_bytes") or d.get("total_bytes_estimate") or 0
67
+ downloaded = d.get("downloaded_bytes") or 0
68
+ speed = d.get("speed") or 0
69
+ eta = d.get("eta") or 0
70
+
71
+ percent = (downloaded / total_bytes * 100.0) if total_bytes > 0 else 0.0
72
+ speed_str = f"{speed / (1024 * 1024):.1f} MB/s" if speed else ""
73
+ eta_str = f"{int(eta)}s" if eta else ""
74
+
75
+ prog = DownloadProgress(
76
+ current_track_idx=track_index,
77
+ total_tracks=total_tracks,
78
+ track_title=track.title,
79
+ status=TrackStatus.DOWNLOADING,
80
+ download_percent=percent,
81
+ speed_str=speed_str,
82
+ eta_str=eta_str,
83
+ )
84
+ progress_callback(prog)
85
+ elif status == "finished":
86
+ prog = DownloadProgress(
87
+ current_track_idx=track_index,
88
+ total_tracks=total_tracks,
89
+ track_title=track.title,
90
+ status=TrackStatus.CONVERTING,
91
+ download_percent=100.0,
92
+ )
93
+ progress_callback(prog)
94
+
95
+ last_err = None
96
+
97
+ for profile_idx, client_profile in enumerate(cls.CLIENT_PROFILES, 1):
98
+ ydl_opts = {
99
+ "format": "bestaudio/best",
100
+ "outtmpl": temp_out_template,
101
+ "noplaylist": True,
102
+ "geo_bypass": True,
103
+ "extractor_args": {
104
+ "youtube": {
105
+ "player_client": client_profile,
106
+ }
107
+ },
108
+ "postprocessors": [
109
+ {
110
+ "key": "FFmpegExtractAudio",
111
+ "preferredcodec": fmt,
112
+ "preferredquality": preferred_quality,
113
+ }
114
+ ],
115
+ "postprocessor_args": {
116
+ "ExtractAudio": ["-id3v2_version", "3", "-write_xing", "1", "-map_metadata", "-1"]
117
+ },
118
+ "quiet": True,
119
+ "no_warnings": True,
120
+ "progress_hooks": [yt_hook],
121
+ "retries": 3,
122
+ "fragment_retries": 3,
123
+ "socket_timeout": 25,
124
+ }
125
+
126
+ try:
127
+ with yt_dlp.YoutubeDL(ydl_opts) as ydl:
128
+ ydl.download([url_to_download])
129
+
130
+ expected_files = list(temp_dir.glob(f"*.{fmt}"))
131
+ if not expected_files:
132
+ expected_files = list(temp_dir.glob("*.*"))
133
+
134
+ if not expected_files:
135
+ raise RuntimeError(f"FFmpeg produced no output audio file for '{track.title}'")
136
+
137
+ generated_file = expected_files[0]
138
+
139
+ if generated_file.stat().st_size < 100_000:
140
+ raise RuntimeError(f"Downloaded audio file is too small ({generated_file.stat().st_size} bytes)")
141
+
142
+ dest_path.parent.mkdir(parents=True, exist_ok=True)
143
+ shutil.move(str(generated_file), str(dest_path))
144
+
145
+ if options.rate_limit_delay > 0:
146
+ delay = options.rate_limit_delay + random.uniform(0.1, 0.4)
147
+ time.sleep(delay)
148
+
149
+ try:
150
+ shutil.rmtree(str(temp_dir), ignore_errors=True)
151
+ except Exception:
152
+ pass
153
+
154
+ return dest_path
155
+
156
+ except Exception as e:
157
+ last_err = e
158
+ time.sleep(0.5 * profile_idx)
159
+
160
+ try:
161
+ shutil.rmtree(str(temp_dir), ignore_errors=True)
162
+ except Exception:
163
+ pass
164
+
165
+ raise RuntimeError(f"Download failed for {url_to_download}: {last_err}")
@@ -0,0 +1,47 @@
1
+ from pathlib import Path
2
+ from typing import Optional, Tuple
3
+ import requests
4
+
5
+ from openaudio.core.models import TrackMetadata
6
+
7
+ class LyricsFetcher:
8
+
9
+ API_URL = "https://lrclib.net/api/get"
10
+ USER_AGENT = "OpenAudio/1.0 (https://github.com/alphap365/openaudio)"
11
+
12
+ @classmethod
13
+ def fetch_lyrics(cls, track: TrackMetadata) -> Tuple[Optional[str], Optional[str]]:
14
+ params = {
15
+ "track_name": track.title,
16
+ "artist_name": track.primary_artist,
17
+ }
18
+ if track.album and track.album != "Single" and track.album != "Unknown Album":
19
+ params["album_name"] = track.album
20
+ if track.duration_seconds > 0:
21
+ params["duration"] = str(int(round(track.duration_seconds)))
22
+
23
+ headers = {"User-Agent": cls.USER_AGENT}
24
+
25
+ try:
26
+ resp = requests.get(cls.API_URL, params=params, headers=headers, timeout=6)
27
+ if resp.status_code == 200:
28
+ data = resp.json()
29
+ plain = data.get("plainLyrics")
30
+ synced = data.get("syncedLyrics")
31
+ return plain, synced
32
+ except Exception:
33
+ pass
34
+
35
+ return None, None
36
+
37
+ @classmethod
38
+ def save_lrc_file(cls, lrc_content: str, audio_file_path: Path) -> Optional[Path]:
39
+ if not lrc_content or not audio_file_path:
40
+ return None
41
+ lrc_path = audio_file_path.with_suffix(".lrc")
42
+ try:
43
+ with open(lrc_path, "w", encoding="utf-8") as f:
44
+ f.write(lrc_content)
45
+ return lrc_path
46
+ except Exception:
47
+ return None
@@ -0,0 +1,161 @@
1
+ import re
2
+ from typing import Dict, List, Optional, Set, Tuple
3
+ from rapidfuzz import fuzz
4
+ import yt_dlp
5
+
6
+ from openaudio.core.models import TrackMetadata
7
+
8
+ class AudioMatcher:
9
+
10
+ YDL_EXTRACTOR_ARGS = {
11
+ "youtube": {
12
+ "player_client": ["android_music", "android", "mweb", "web"],
13
+ }
14
+ }
15
+
16
+ @classmethod
17
+ def get_ranked_candidates(
18
+ cls,
19
+ track: TrackMetadata,
20
+ exclude_ids: Optional[Set[str]] = None,
21
+ ) -> List[Tuple[str, float]]:
22
+ excluded = exclude_ids or set()
23
+ candidates: Dict[str, float] = {}
24
+
25
+ if track.youtube_url and track.source_provider == "youtube":
26
+ vid = track.youtube_id or (track.youtube_url.split("v=")[1].split("&")[0] if "v=" in track.youtube_url else "")
27
+ if vid and vid not in excluded:
28
+ candidates[track.youtube_url] = 100.0
29
+
30
+ clean_title = re.sub(r"\s*[\(\[].*?[\)\]]", "", track.title).strip()
31
+ queries = [
32
+ f"ytsearch6:{track.primary_artist} - {clean_title} Official Audio",
33
+ f"ytsearch6:{track.primary_artist} {clean_title} audio",
34
+ f"ytsearch6:{clean_title} {track.primary_artist}",
35
+ f"ytsearch6:{track.title} {track.primary_artist}",
36
+ ]
37
+
38
+ ydl_opts = {
39
+ "extract_flat": True,
40
+ "skip_download": True,
41
+ "quiet": True,
42
+ "no_warnings": True,
43
+ "geo_bypass": True,
44
+ "extractor_args": cls.YDL_EXTRACTOR_ARGS,
45
+ }
46
+
47
+ with yt_dlp.YoutubeDL(ydl_opts) as ydl:
48
+ for query in queries:
49
+ try:
50
+ res = ydl.extract_info(query, download=False)
51
+ except Exception:
52
+ continue
53
+
54
+ if not res or "entries" not in res:
55
+ continue
56
+
57
+ for entry in res.get("entries", []):
58
+ if not entry:
59
+ continue
60
+ video_id = entry.get("id")
61
+ if not video_id or video_id in excluded:
62
+ continue
63
+
64
+ url = entry.get("url") or f"https://www.youtube.com/watch?v={video_id}"
65
+ score = cls._score_candidate(track, entry)
66
+ if url not in candidates or score > candidates[url]:
67
+ candidates[url] = score
68
+
69
+ ranked = sorted(candidates.items(), key=lambda x: x[1], reverse=True)
70
+ return ranked
71
+
72
+ @classmethod
73
+ def match_track(
74
+ cls,
75
+ track: TrackMetadata,
76
+ force_search: bool = False,
77
+ exclude_ids: Optional[Set[str]] = None,
78
+ ) -> Tuple[str, float]:
79
+ excluded = exclude_ids or set()
80
+ if not force_search and track.youtube_url and track.source_provider == "youtube":
81
+ vid = track.youtube_id or (track.youtube_url.split("v=")[1].split("&")[0] if "v=" in track.youtube_url else "")
82
+ if vid and vid not in excluded:
83
+ return track.youtube_url, 100.0
84
+
85
+ candidates = cls.get_ranked_candidates(track, exclude_ids=excluded)
86
+ if not candidates:
87
+ raise RuntimeError(f"No active YouTube audio candidates found for '{track.artist_str} - {track.title}'")
88
+
89
+ best_url, best_score = candidates[0]
90
+ track.youtube_url = best_url
91
+ if "v=" in best_url:
92
+ track.youtube_id = best_url.split("v=")[1].split("&")[0]
93
+
94
+ return best_url, best_score
95
+
96
+ @classmethod
97
+ def _score_candidate(cls, target: TrackMetadata, candidate: dict) -> float:
98
+ cand_title = candidate.get("title", "").lower()
99
+ cand_channel = (candidate.get("uploader") or candidate.get("channel") or "").lower()
100
+ cand_duration = float(candidate.get("duration", 0) or 0)
101
+
102
+ target_title = target.title.lower()
103
+ target_artist = target.primary_artist.lower()
104
+ target_duration = target.duration_seconds
105
+
106
+ score = 0.0
107
+
108
+ cleaned_cand_title = re.sub(
109
+ r"[\(\[](official\s*(audio|video|music\s*video|lyric\s*video|hd|4k)?|lyrics|audio)[\)\]]",
110
+ "",
111
+ cand_title,
112
+ flags=re.IGNORECASE,
113
+ ).strip()
114
+
115
+ title_ratio = fuzz.token_set_ratio(target_title, cleaned_cand_title)
116
+ score += (title_ratio / 100.0) * 45.0
117
+
118
+ artist_in_channel = fuzz.partial_ratio(target_artist, cand_channel) >= 70
119
+ artist_in_title = fuzz.partial_ratio(target_artist, cand_title) >= 70
120
+ if artist_in_channel or artist_in_title:
121
+ score += 25.0
122
+ else:
123
+ for extra_art in target.artists[1:]:
124
+ if fuzz.partial_ratio(extra_art.lower(), cand_title) >= 70 or fuzz.partial_ratio(extra_art.lower(), cand_channel) >= 70:
125
+ score += 15.0
126
+ break
127
+
128
+ if target_duration > 0 and cand_duration > 0:
129
+ diff = abs(target_duration - cand_duration)
130
+ if diff <= 4.0:
131
+ score += 20.0
132
+ elif diff <= 8.0:
133
+ score += 15.0
134
+ elif diff <= 15.0:
135
+ score += 5.0
136
+ elif diff <= 30.0:
137
+ score -= 15.0
138
+ else:
139
+ score -= 40.0
140
+ else:
141
+ score += 10.0
142
+
143
+ if cand_channel.endswith("- topic"):
144
+ score += 10.0
145
+ elif "official audio" in cand_title or "official lyric video" in cand_title or "official music video" in cand_title:
146
+ score += 6.0
147
+
148
+ unwanted_keywords = [
149
+ "cover", "karaoke", "live", "concert", "reaction",
150
+ "slowed", "reverb", "8d audio", "1 hour", "10 hours",
151
+ "extended mix", "tribute", "instrumental"
152
+ ]
153
+
154
+ for kw in unwanted_keywords:
155
+ if kw in cand_title and kw not in target_title:
156
+ if kw in ("cover", "karaoke", "reaction", "1 hour", "10 hours"):
157
+ score -= 40.0
158
+ else:
159
+ score -= 20.0
160
+
161
+ return max(0.0, min(100.0, score))
@@ -0,0 +1,111 @@
1
+ from dataclasses import dataclass, field
2
+ from enum import Enum
3
+ from pathlib import Path
4
+ from typing import List, Optional
5
+
6
+ class TrackStatus(str, Enum):
7
+ QUEUED = "queued"
8
+ MATCHING = "matching"
9
+ DOWNLOADING = "downloading"
10
+ CONVERTING = "converting"
11
+ TAGGING = "tagging"
12
+ COMPLETED = "completed"
13
+ SKIPPED = "skipped"
14
+ FAILED = "failed"
15
+
16
+ @dataclass
17
+ class TrackMetadata:
18
+ title: str
19
+ artists: List[str] = field(default_factory=list)
20
+ album: str = "Unknown Album"
21
+ album_artist: str = ""
22
+ duration_seconds: float = 0.0
23
+ track_number: int = 1
24
+ total_tracks: int = 1
25
+ disc_number: int = 1
26
+ release_year: Optional[str] = None
27
+ isrc: Optional[str] = None
28
+ genre: Optional[str] = None
29
+ cover_url: Optional[str] = None
30
+ lyrics: Optional[str] = None
31
+ source_url: Optional[str] = None
32
+ source_id: Optional[str] = None
33
+ source_provider: str = "unknown"
34
+ youtube_id: Optional[str] = None
35
+ youtube_url: Optional[str] = None
36
+
37
+ @property
38
+ def artist_str(self) -> str:
39
+ if not self.artists:
40
+ return "Unknown Artist"
41
+ return ", ".join(self.artists)
42
+
43
+ @property
44
+ def primary_artist(self) -> str:
45
+ if self.artists:
46
+ return self.artists[0]
47
+ return "Unknown Artist"
48
+
49
+ def __post_init__(self):
50
+ if not self.album_artist and self.artists:
51
+ self.album_artist = self.artists[0]
52
+
53
+ @dataclass
54
+ class PlaylistInfo:
55
+ title: str
56
+ author: str = "Unknown"
57
+ description: str = ""
58
+ cover_url: Optional[str] = None
59
+ tracks: List[TrackMetadata] = field(default_factory=list)
60
+ source_url: str = ""
61
+ source_type: str = "playlist"
62
+
63
+ @property
64
+ def total_tracks(self) -> int:
65
+ return len(self.tracks)
66
+
67
+ @dataclass
68
+ class DownloadOptions:
69
+ format: str = "mp3"
70
+ bitrate: str = "320k"
71
+ output_dir: Path = field(default_factory=lambda: Path.cwd() / "Music")
72
+ sequential_naming: bool = True
73
+ naming_template: str = "{index:03d} - {title} - {artist}"
74
+ fetch_lyrics: bool = True
75
+ save_lrc: bool = False
76
+ embed_cover: bool = True
77
+ overwrite: bool = False
78
+ max_retries: int = 3
79
+ rate_limit_delay: float = 1.2
80
+ mobile_mode: bool = False
81
+ concurrent_downloads: int = 3
82
+ quiet: bool = False
83
+
84
+ def get_audio_quality_args(self) -> List[str]:
85
+ fmt = self.format.lower()
86
+ if fmt == "mp3":
87
+ br = self.bitrate if self.bitrate.endswith("k") else f"{self.bitrate}k"
88
+ return ["-c:a", "libmp3lame", "-b:a", br]
89
+ elif fmt == "flac":
90
+ return ["-c:a", "flac", "-compression_level", "8"]
91
+ elif fmt == "wav":
92
+ return ["-c:a", "pcm_s16le"]
93
+ elif fmt == "opus":
94
+ br = self.bitrate if self.bitrate.endswith("k") else "160k"
95
+ return ["-c:a", "libopus", "-b:a", br, "-vbr", "on"]
96
+ elif fmt == "m4a":
97
+ br = self.bitrate if self.bitrate.endswith("k") else "256k"
98
+ return ["-c:a", "aac", "-b:a", br]
99
+ return ["-c:a", "libmp3lame", "-b:a", "320k"]
100
+
101
+ @dataclass
102
+ class DownloadProgress:
103
+ current_track_idx: int = 0
104
+ total_tracks: int = 0
105
+ track_title: str = ""
106
+ status: TrackStatus = TrackStatus.QUEUED
107
+ download_percent: float = 0.0
108
+ speed_str: str = ""
109
+ eta_str: str = ""
110
+ error_message: Optional[str] = None
111
+ output_path: Optional[Path] = None